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

namespace Indotalent.Features.Sales.Invoice;

public class InvoiceService : BaseService
{
    private readonly RestClient _client;

    public InvoiceService(
            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<GetInvoiceListResponse>>?> GetInvoiceListAsync()
    {
        var request = new RestRequest("api/invoice", Method.Get);
        return await ExecuteWithResponseAsync<List<GetInvoiceListResponse>>(_client, request);
    }

    public async Task<ApiResponse<GetInvoiceByIdResponse>?> GetInvoiceByIdAsync(string id)
    {
        var request = new RestRequest($"api/invoice/{id}", Method.Get);
        return await ExecuteWithResponseAsync<GetInvoiceByIdResponse>(_client, request);
    }

    public async Task<ApiResponse<GetInvoiceByIdResponse>?> GetSalesOrderDetailForInvoiceAsync(string soId)
    {
        var request = new RestRequest($"api/invoice/sales-order-detail/{soId}", Method.Get);
        return await ExecuteWithResponseAsync<GetInvoiceByIdResponse>(_client, request);
    }

    public async Task<ApiResponse<InvoiceLookupResponse>?> GetInvoiceLookupAsync()
    {
        var request = new RestRequest("api/invoice/lookup", Method.Get);
        return await ExecuteWithResponseAsync<InvoiceLookupResponse>(_client, request);
    }

    public async Task<ApiResponse<CreateInvoiceResponse>?> CreateInvoiceAsync(CreateInvoiceRequest data)
    {
        var request = new RestRequest("api/invoice", Method.Post);
        request.AddJsonBody(data);
        return await ExecuteWithResponseAsync<CreateInvoiceResponse>(_client, request);
    }

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

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