// EN: Merchant API service — handles merchant registration and shop management.
// VI: Service API Merchant — xử lý đăng ký merchant và quản lý shop.

using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.JSInterop;
using WebClientTpos.Shared.DTOs;

namespace WebClientTpos.Client.Services;

/// <summary>
/// EN: Service for Merchant and Shop API calls.
/// VI: Service cho các API call Merchant và Shop.
/// </summary>
public class MerchantApiService
{
    private readonly HttpClient _http;

    public MerchantApiService(HttpClient http)
    {
        _http = http;
    }

    /// <summary>
    /// EN: Register current user as a merchant.
    /// VI: Đăng ký user hiện tại làm merchant.
    /// </summary>
    public async Task<(MerchantRegisterResult? Result, string? Error)> RegisterMerchantAsync(MerchantRegisterDto dto)
    {
        try
        {
            await AttachTokenAsync();
            var response = await _http.PostAsJsonAsync("/api/merchants/api/v1/merchants/register", dto);

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadFromJsonAsync<MerchantRegisterResult>();
                return (result, null);
            }

            var error = await ParseErrorAsync(response);
            return (null, error);
        }
        catch (Exception ex)
        {
            return (null, $"Lỗi kết nối: {ex.Message}");
        }
    }

    /// <summary>
    /// EN: Create a new shop for the current merchant.
    /// VI: Tạo shop mới cho merchant hiện tại.
    /// </summary>
    public async Task<(ShopCreateResult? Result, string? Error)> CreateShopAsync(ShopCreateDto dto)
    {
        try
        {
            await AttachTokenAsync();
            var response = await _http.PostAsJsonAsync("/api/merchants/api/v1/shops", dto);

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadFromJsonAsync<ShopCreateResult>();
                return (result, null);
            }

            var error = await ParseErrorAsync(response);
            return (null, error);
        }
        catch (Exception ex)
        {
            return (null, $"Lỗi kết nối: {ex.Message}");
        }
    }

    /// <summary>
    /// EN: Update an existing shop.
    /// VI: Cập nhật shop hiện tại.
    /// </summary>
    public async Task<(bool Success, string? Error)> UpdateShopAsync(Guid shopId, ShopUpdateDto dto)
    {
        try
        {
            await AttachTokenAsync();
            var response = await _http.PutAsJsonAsync($"/api/merchants/api/v1/shops/{shopId}", dto);

            if (response.IsSuccessStatusCode)
                return (true, null);

            var error = await ParseErrorAsync(response);
            return (false, error);
        }
        catch (Exception ex)
        {
            return (false, $"Lỗi kết nối: {ex.Message}");
        }
    }

    /// <summary>
    /// EN: Deactivate a shop (temporarily disable operations).
    /// VI: Tạm ngưng hoạt động shop (vô hiệu hóa tạm thời).
    /// </summary>
    public async Task<bool> DeactivateShopAsync(Guid shopId)
    {
        try
        {
            await AttachTokenAsync();
            var response = await _http.PostAsync($"/api/bff/shops/{shopId}/deactivate", null);
            return response.IsSuccessStatusCode;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// EN: Permanently close a shop.
    /// VI: Đóng shop vĩnh viễn.
    /// </summary>
    public async Task<bool> CloseShopAsync(Guid shopId)
    {
        try
        {
            await AttachTokenAsync();
            var response = await _http.PostAsync($"/api/bff/shops/{shopId}/close", null);
            return response.IsSuccessStatusCode;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// EN: Attach Bearer token to HttpClient for authorized requests.
    /// VI: Gắn Bearer token vào HttpClient cho các request cần xác thực.
    /// </summary>
    // EN: Auth is handled by the BFF httpOnly session cookie — no manual token attachment needed.
    // VI: Auth được xử lý bởi BFF httpOnly session cookie — không cần gắn token thủ công.
    private static Task AttachTokenAsync() => Task.CompletedTask;

    /// <summary>
    /// EN: Parse error from API response.
    /// VI: Parse lỗi từ API response.
    /// </summary>
    private static async Task<string> ParseErrorAsync(HttpResponseMessage response)
    {
        try
        {
            var content = await response.Content.ReadAsStringAsync();
            using var doc = JsonDocument.Parse(content);
            if (doc.RootElement.TryGetProperty("detail", out var detail))
                return detail.GetString() ?? "Lỗi không xác định";
            if (doc.RootElement.TryGetProperty("title", out var title))
                return title.GetString() ?? "Lỗi không xác định";
            return content.Length > 200 ? content[..200] : content;
        }
        catch
        {
            return $"Lỗi ({response.StatusCode})";
        }
    }
}
