using Indotalent.ConfigBackEnd.Interfaces;
using Indotalent.ConfigFrontEnd.Common;
using Indotalent.Features.Sales.CreditNote.Cqrs;
using Indotalent.Infrastructure.Authentication.Identity;
using Indotalent.Shared.Models;
using Microsoft.AspNetCore.Components;
using MudBlazor;
using RestSharp;

namespace Indotalent.Features.Sales.CreditNote;

public class CreditNoteService : BaseService
{
    private readonly RestClient _client;

    public CreditNoteService(
            IHttpClientFactory clientFactory,
            NavigationManager nav,
            ISnackbar snackbar,
            ICurrentUserService currentUserService,
            TokenProvider tokenProvider)
            : base(clientFactory, nav, snackbar, currentUserService, tokenProvider)
    {
        _client = new RestClient(nav.BaseUri);
    }

    public async Task<ApiResponse<List<GetCreditNoteListResponse>>?> GetCreditNoteListAsync()
    {
        var request = new RestRequest("api/credit-note", Method.Get);
        return await ExecuteWithResponseAsync<List<GetCreditNoteListResponse>>(_client, request);
    }

    public async Task<ApiResponse<GetCreditNoteByIdResponse>?> GetCreditNoteByIdAsync(string id)
    {
        var request = new RestRequest($"api/credit-note/{id}", Method.Get);
        return await ExecuteWithResponseAsync<GetCreditNoteByIdResponse>(_client, request);
    }

    public async Task<ApiResponse<GetCreditNoteByIdResponse>?> GetSalesReturnDetailForCreditNoteAsync(string srId)
    {
        var request = new RestRequest($"api/credit-note/sales-return-detail/{srId}", Method.Get);
        return await ExecuteWithResponseAsync<GetCreditNoteByIdResponse>(_client, request);
    }

    public async Task<ApiResponse<CreditNoteLookupResponse>?> GetCreditNoteLookupAsync()
    {
        var request = new RestRequest("api/credit-note/lookup", Method.Get);
        return await ExecuteWithResponseAsync<CreditNoteLookupResponse>(_client, request);
    }

    public async Task<ApiResponse<CreateCreditNoteResponse>?> CreateCreditNoteAsync(CreateCreditNoteRequest data)
    {
        var request = new RestRequest("api/credit-note", Method.Post);
        request.AddJsonBody(data);
        return await ExecuteWithResponseAsync<CreateCreditNoteResponse>(_client, request);
    }

    public async Task<ApiResponse<bool>?> UpdateCreditNoteAsync(UpdateCreditNoteRequest data)
    {
        var request = new RestRequest("api/credit-note/update", Method.Post);
        request.AddJsonBody(data);
        return await ExecuteWithResponseAsync<bool>(_client, request);
    }

    public async Task<bool> DeleteCreditNoteByIdAsync(string id)
    {
        var request = new RestRequest($"api/credit-note/delete/{id}", Method.Post);
        var response = await ExecuteWithResponseAsync<object>(_client, request);
        return response?.IsSuccess ?? false;
    }
}