using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using WebClientTpos.Server.Infrastructure;

namespace WebClientTpos.Server.Controllers;

/// <summary>
/// EN: Membership controller — proxies to MembershipService for members and levels.
/// VI: Controller thành viên — proxy đến MembershipService cho thành viên và cấp bậc.
/// </summary>
[ApiController]
[Route("api/bff")]
public class MembershipController : ControllerBase
{
    private readonly HttpClient _membership;

    public MembershipController(IHttpClientFactory httpClientFactory)
    {
        _membership = httpClientFactory.CreateClient("MembershipService");
    }

    /// <summary>
    /// EN: Get all members (customers).
    /// VI: Lấy danh sách thành viên (khách hàng).
    /// </summary>
    [HttpGet("members")]
    public Task<IActionResult> GetMembers([FromQuery] string? search = null, [FromQuery] int pageSize = 100)
    {
        var qs = $"?pageSize={pageSize}";
        if (!string.IsNullOrWhiteSpace(search)) qs += $"&search={Uri.EscapeDataString(search)}";
        return _membership.GetAsync($"/api/v1/members{qs}").ProxyAsync();
    }

    /// <summary>
    /// EN: Get a member by ID.
    /// VI: Lấy thành viên theo ID.
    /// </summary>
    [HttpGet("members/{memberId:guid}")]
    public Task<IActionResult> GetMemberById(Guid memberId) =>
        _membership.GetAsync($"/api/v1/members/{memberId}").ProxyAsync();

    /// <summary>
    /// EN: Create a member.
    /// VI: Tạo thành viên.
    /// </summary>
    [HttpPost("members")]
    public async Task<IActionResult> CreateMember([FromBody] JsonElement body)
    {
        // EN: Generate a unique userId for each new customer (not tied to the admin user).
        // VI: Tạo userId duy nhất cho mỗi khách hàng mới (không gắn với admin user).
        var rawJson = body.GetRawText();
        if (!rawJson.Contains("\"userId\""))
        {
            var newUserId = Guid.NewGuid();
            rawJson = rawJson.TrimEnd('}') + $",\"userId\":\"{newUserId}\"}}";
        }
        var httpContent = new StringContent(rawJson, System.Text.Encoding.UTF8, "application/json");
        return await _membership.PostAsync("/api/v1/members", httpContent).ProxyAsync();
    }

    /// <summary>
    /// EN: Update a member.
    /// VI: Cập nhật thành viên.
    /// </summary>
    [HttpPut("members/{memberId:guid}")]
    public Task<IActionResult> UpdateMember(Guid memberId, [FromBody] JsonElement body) =>
        _membership.PutAsJsonAsync($"/api/v1/members/{memberId}", body).ProxyAsync();

    /// <summary>
    /// EN: Soft-delete a member.
    /// VI: Xóa mềm thành viên.
    /// </summary>
    [HttpDelete("members/{memberId:guid}")]
    public Task<IActionResult> DeleteMember(Guid memberId) =>
        _membership.DeleteAsync($"/api/v1/members/{memberId}").ProxyAsync();

    /// <summary>
    /// EN: Get membership level definitions with member counts.
    /// VI: Lấy định nghĩa cấp bậc membership với số lượng thành viên.
    /// </summary>
    [HttpGet("membership/levels")]
    public Task<IActionResult> GetMembershipLevels() =>
        _membership.GetAsync("/api/v1/levels").ProxyAsync();

    // ═══ LEVEL CRUD ═══

    /// <summary>
    /// EN: Create a membership level.
    /// VI: Tạo cấp bậc membership.
    /// </summary>
    [HttpPost("membership/levels")]
    public Task<IActionResult> CreateLevel([FromBody] JsonElement body) =>
        _membership.PostAsJsonAsync("/api/v1/levels", body).ProxyAsync();

    /// <summary>
    /// EN: Update a membership level.
    /// VI: Cập nhật cấp bậc membership.
    /// </summary>
    [HttpPut("membership/levels/{id:guid}")]
    public Task<IActionResult> UpdateLevel(Guid id, [FromBody] JsonElement body) =>
        _membership.PutAsJsonAsync($"/api/v1/levels/{id}", body).ProxyAsync();

    /// <summary>
    /// EN: Deactivate a membership level.
    /// VI: Vô hiệu hóa cấp bậc membership.
    /// </summary>
    [HttpDelete("membership/levels/{id:guid}")]
    public Task<IActionResult> DeleteLevel(Guid id) =>
        _membership.DeleteAsync($"/api/v1/levels/{id}").ProxyAsync();

    // ═══ EXPERIENCE MANAGEMENT ═══

    /// <summary>
    /// EN: Add experience points to a member.
    /// VI: Cộng điểm kinh nghiệm cho thành viên.
    /// </summary>
    [HttpPost("members/{memberId:guid}/experience")]
    public Task<IActionResult> AddExperience(Guid memberId, [FromBody] JsonElement body) =>
        _membership.PostAsJsonAsync($"/api/v1/members/{memberId}/experience", body).ProxyAsync();

    /// <summary>
    /// EN: Get member level progress.
    /// VI: Lấy tiến trình cấp bậc thành viên.
    /// </summary>
    [HttpGet("members/{memberId:guid}/progress")]
    public Task<IActionResult> GetMemberProgress(Guid memberId) =>
        _membership.GetAsync($"/api/v1/members/{memberId}/progress").ProxyAsync();

    /// <summary>
    /// EN: Get member experience history.
    /// VI: Lấy lịch sử điểm kinh nghiệm thành viên.
    /// </summary>
    [HttpGet("members/{memberId:guid}/experience")]
    public Task<IActionResult> GetExperienceHistory(Guid memberId, [FromQuery] int pageSize = 20) =>
        _membership.GetAsync($"/api/v1/members/{memberId}/experience?pageSize={pageSize}").ProxyAsync();
}
