using Asp.Versioning;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using MktXService.API.Application.Commands;
using MktXService.API.Application.Queries;

namespace MktXService.API.Controllers;

/// <summary>
/// EN: Controller for Twitter Account management.
/// VI: Controller quản lý tài khoản Twitter.
/// </summary>
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[Produces("application/json")]
public class AccountsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<AccountsController> _logger;

    public AccountsController(IMediator mediator, ILogger<AccountsController> logger)
    {
        _mediator = mediator;
        _logger = logger;
    }

    /// <summary>
    /// EN: Get all Twitter accounts for a merchant.
    /// VI: Lấy tất cả tài khoản Twitter của merchant.
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(IEnumerable<TwitterAccountDto>), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetAccounts([FromQuery] Guid merchantId)
    {
        var accounts = await _mediator.Send(new GetTwitterAccountsQuery(merchantId));
        return Ok(new { success = true, data = accounts });
    }

    /// <summary>
    /// EN: Get a Twitter account by ID.
    /// VI: Lấy tài khoản Twitter theo ID.
    /// </summary>
    [HttpGet("{id:guid}")]
    [ProducesResponseType(typeof(TwitterAccountDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetAccount(Guid id)
    {
        var account = await _mediator.Send(new GetTwitterAccountQuery(id));
        if (account == null)
            return NotFound(new { success = false, error = new { code = "ACCOUNT_NOT_FOUND", message = $"Account {id} not found" } });

        return Ok(new { success = true, data = account });
    }

    /// <summary>
    /// EN: Connect a new Twitter account via OAuth.
    /// VI: Kết nối tài khoản Twitter mới qua OAuth.
    /// </summary>
    [HttpPost("connect")]
    [ProducesResponseType(typeof(ConnectTwitterAccountResult), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> ConnectAccount([FromBody] ConnectAccountRequest request)
    {
        var command = new ConnectTwitterAccountCommand(
            request.MerchantId,
            request.TwitterUserId,
            request.Username,
            request.OAuthToken,
            request.OAuthTokenSecret,
            request.DisplayName,
            request.ProfileImageUrl);

        var result = await _mediator.Send(command);

        if (!result.Success)
            return BadRequest(new { success = false, error = new { code = "CONNECTION_FAILED", message = result.Error } });

        return CreatedAtAction(nameof(GetAccount), new { id = result.AccountId },
            new { success = true, data = result });
    }

    /// <summary>
    /// EN: Disconnect a Twitter account.
    /// VI: Ngắt kết nối tài khoản Twitter.
    /// </summary>
    [HttpPost("{id:guid}/disconnect")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> DisconnectAccount(Guid id)
    {
        var result = await _mediator.Send(new DisconnectTwitterAccountCommand(id));
        if (!result)
            return NotFound(new { success = false, error = new { code = "ACCOUNT_NOT_FOUND", message = $"Account {id} not found" } });

        return Ok(new { success = true, message = "Account disconnected successfully" });
    }

    /// <summary>
    /// EN: Refresh OAuth tokens.
    /// VI: Làm mới OAuth tokens.
    /// </summary>
    [HttpPost("{id:guid}/refresh-tokens")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> RefreshTokens(Guid id, [FromBody] RefreshTokensRequest request)
    {
        var result = await _mediator.Send(new RefreshTwitterAccountTokensCommand(id, request.OAuthToken, request.OAuthTokenSecret));
        if (!result)
            return NotFound(new { success = false, error = new { code = "ACCOUNT_NOT_FOUND", message = $"Account {id} not found" } });

        return Ok(new { success = true, message = "Tokens refreshed successfully" });
    }
}

#region Request Models

public record ConnectAccountRequest(
    Guid MerchantId,
    string TwitterUserId,
    string Username,
    string OAuthToken,
    string OAuthTokenSecret,
    string? DisplayName = null,
    string? ProfileImageUrl = null);

public record RefreshTokensRequest(string OAuthToken, string OAuthTokenSecret);

#endregion
