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

namespace Indotalent.Features.Purchase.Bill;

public class BillService : BaseService
{
    private readonly RestClient _client;

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

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

    public async Task<ApiResponse<GetBillByIdResponse>?> GetPurchaseOrderDetailForBillAsync(string poId)
    {
        var request = new RestRequest($"api/bill/purchase-order-detail/{poId}", Method.Get);
        return await ExecuteWithResponseAsync<GetBillByIdResponse>(_client, request);
    }

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

    public async Task<ApiResponse<CreateBillResponse>?> CreateBillAsync(CreateBillRequest data)
    {
        var request = new RestRequest("api/bill", Method.Post);
        request.AddJsonBody(data);
        return await ExecuteWithResponseAsync<CreateBillResponse>(_client, request);
    }

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

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