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

namespace WebClientTpos.Server.Controllers;

/// <summary>
/// EN: Account controller — proxies to IAM and Merchant services for owner account management.
/// VI: Controller tài khoản — proxy đến IAM và Merchant cho quản lý tài khoản chủ doanh nghiệp.
/// </summary>
[ApiController]
[Route("api/bff/account")]
public class AccountController : ControllerBase
{
    private readonly HttpClient _iam;
    private readonly HttpClient _merchant;

    public AccountController(IHttpClientFactory httpClientFactory)
    {
        _iam = httpClientFactory.CreateClient("IamService");
        _merchant = httpClientFactory.CreateClient("MerchantService");
    }

    // ═══ USER PROFILE ═══

    /// <summary>
    /// EN: Get current user info from IAM (id, email, firstName, lastName, roles).
    /// VI: Lấy thông tin user hiện tại từ IAM (id, email, firstName, lastName, vai trò).
    /// </summary>
    [HttpGet("me")]
    public async Task<IActionResult> GetMe()
    {
        var userId = ExtractUserIdFromJwt();
        if (userId == null) return Unauthorized(new { success = false, message = "Not authenticated" });
        return await _iam.GetAsync($"/api/v1/users/{userId}").ProxyAsync();
    }

    /// <summary>
    /// EN: Get user profile (bio, avatar, timezone, locale, address, phone).
    /// VI: Lấy profile user (bio, avatar, timezone, ngôn ngữ, địa chỉ, SĐT).
    /// </summary>
    [HttpGet("profile")]
    public async Task<IActionResult> GetProfile()
    {
        var userId = ExtractUserIdFromJwt();
        if (userId == null) return Unauthorized(new { success = false, message = "Not authenticated" });
        return await _iam.GetAsync($"/api/v1/users/{userId}/profile").ProxyAsync();
    }

    /// <summary>
    /// EN: Update user profile (bio, timezone, locale, avatarUrl).
    /// VI: Cập nhật profile (bio, timezone, ngôn ngữ, avatarUrl).
    /// </summary>
    [HttpPut("profile")]
    public async Task<IActionResult> UpdateProfile([FromBody] JsonElement body)
    {
        var userId = ExtractUserIdFromJwt();
        if (userId == null) return Unauthorized(new { success = false, message = "Not authenticated" });
        return await _iam.PutAsJsonAsync($"/api/v1/users/{userId}/profile", body).ProxyAsync();
    }

    /// <summary>
    /// EN: Update user basic info (firstName, lastName).
    /// VI: Cập nhật tên user (firstName, lastName).
    /// </summary>
    [HttpPut("me")]
    public async Task<IActionResult> UpdateMe([FromBody] JsonElement body)
    {
        var userId = ExtractUserIdFromJwt();
        if (userId == null) return Unauthorized(new { success = false, message = "Not authenticated" });
        return await _iam.PutAsJsonAsync($"/api/v1/users/{userId}", body).ProxyAsync();
    }

    // ═══ MERCHANT PROFILE ═══

    /// <summary>
    /// EN: Get current merchant profile.
    /// VI: Lấy thông tin merchant hiện tại.
    /// </summary>
    [HttpGet("merchant")]
    public Task<IActionResult> GetMerchant() =>
        _merchant.GetAsync("/api/v1/merchants/me").ProxyAsync();

    /// <summary>
    /// EN: Update merchant profile (businessName, etc).
    /// VI: Cập nhật thông tin merchant (tên doanh nghiệp, ...).
    /// </summary>
    [HttpPut("merchant")]
    public Task<IActionResult> UpdateMerchant([FromBody] JsonElement body) =>
        _merchant.PutAsJsonAsync("/api/v1/merchants/me", body).ProxyAsync();

    // ═══ SECURITY ═══

    /// <summary>
    /// EN: Change password.
    /// VI: Đổi mật khẩu.
    /// </summary>
    [HttpPost("change-password")]
    public Task<IActionResult> ChangePassword([FromBody] JsonElement body) =>
        _iam.PostAsJsonAsync("/api/v1/auth/change-password", body).ProxyAsync();

    /// <summary>
    /// EN: Enable 2FA — returns QR code and recovery codes.
    /// VI: Bật 2FA — trả về QR code và mã khôi phục.
    /// </summary>
    [HttpPost("2fa/enable")]
    public Task<IActionResult> Enable2FA() =>
        _iam.PostAsync("/api/v1/auth/2fa/enable", null).ProxyAsync();

    /// <summary>
    /// EN: Verify 2FA code to complete setup.
    /// VI: Xác thực mã 2FA để hoàn tất thiết lập.
    /// </summary>
    [HttpPost("2fa/verify")]
    public Task<IActionResult> Verify2FA([FromBody] JsonElement body) =>
        _iam.PostAsJsonAsync("/api/v1/auth/2fa/verify", body).ProxyAsync();

    /// <summary>
    /// EN: Disable 2FA.
    /// VI: Tắt 2FA.
    /// </summary>
    [HttpPost("2fa/disable")]
    public Task<IActionResult> Disable2FA([FromBody] JsonElement body) =>
        _iam.PostAsJsonAsync("/api/v1/auth/2fa/disable", body).ProxyAsync();

    /// <summary>
    /// EN: Get linked OAuth accounts (Google, Facebook).
    /// VI: Lấy tài khoản liên kết (Google, Facebook).
    /// </summary>
    [HttpGet("linked-accounts")]
    public Task<IActionResult> GetLinkedAccounts() =>
        _iam.GetAsync("/api/v1/auth/linked-accounts").ProxyAsync();

    /// <summary>
    /// EN: Logout and revoke tokens.
    /// VI: Đăng xuất và thu hồi token.
    /// </summary>
    [HttpPost("logout")]
    public Task<IActionResult> Logout() =>
        _iam.PostAsync("/api/v1/auth/logout", null).ProxyAsync();

    // ═══ SUBSCRIPTION ═══

    /// <summary>
    /// EN: Get current subscription info.
    /// VI: Lấy thông tin gói dịch vụ hiện tại.
    /// </summary>
    [HttpGet("subscription")]
    public Task<IActionResult> GetSubscription() =>
        _merchant.GetAsync("/api/v1/subscriptions/me").ProxyAsync();

    /// <summary>
    /// EN: Get available subscription plans.
    /// VI: Lấy danh sách gói dịch vụ.
    /// </summary>
    [HttpGet("subscription/plans")]
    public Task<IActionResult> GetPlans() =>
        _merchant.GetAsync("/api/v1/subscriptions/plans").ProxyAsync();

    /// <summary>
    /// EN: Subscribe or upgrade to a plan.
    /// VI: Đăng ký hoặc nâng cấp gói.
    /// </summary>
    [HttpPost("subscription/subscribe")]
    public Task<IActionResult> Subscribe([FromBody] JsonElement body) =>
        _merchant.PostAsJsonAsync("/api/v1/subscriptions/subscribe", body).ProxyAsync();

    /// <summary>
    /// EN: Get current usage vs limits.
    /// VI: Lấy mức sử dụng hiện tại so với giới hạn.
    /// </summary>
    [HttpGet("subscription/usage")]
    public Task<IActionResult> GetUsage() =>
        _merchant.GetAsync("/api/v1/subscriptions/usage").ProxyAsync();

    // ═══ HELPERS ═══

    private string? ExtractUserIdFromJwt()
    {
        var authHeader = Request.Headers["Authorization"].FirstOrDefault();
        if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
            return null;
        try
        {
            var token = authHeader["Bearer ".Length..];
            var parts = token.Split('.');
            if (parts.Length < 2) return null;
            var payload = parts[1].Replace('-', '+').Replace('_', '/');
            switch (payload.Length % 4) { case 2: payload += "=="; break; case 3: payload += "="; break; }
            using var jwtDoc = JsonDocument.Parse(Convert.FromBase64String(payload));
            return jwtDoc.RootElement.TryGetProperty("sub", out var sub) ? sub.GetString() : null;
        }
        catch { return null; }
    }
}
