using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using WhatsAppService.API.Application.Commands;
using WhatsAppService.Domain.AggregatesModel.WhatsAppAccountAggregate;

namespace WhatsAppService.API.Controllers;

/// <summary>
/// EN: Controller for managing WhatsApp accounts.
/// VI: Controller để quản lý WhatsApp accounts.
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Produces("application/json")]
[Authorize]
public class WhatsAppAccountsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly IWhatsAppAccountRepository _repository;
    private readonly ILogger<WhatsAppAccountsController> _logger;

    public WhatsAppAccountsController(
        IMediator mediator,
        IWhatsAppAccountRepository repository,
        ILogger<WhatsAppAccountsController> logger)
    {
        _mediator = mediator;
        _repository = repository;
        _logger = logger;
    }

    /// <summary>
    /// EN: Connect a WhatsApp Business Account.
    /// VI: Kết nối WhatsApp Business Account.
    /// </summary>
    [HttpPost]
    [ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> Connect([FromBody] ConnectAccountRequest request)
    {
        var command = new ConnectWhatsAppAccountCommand(
            request.ShopId,
            request.PhoneNumberId,
            request.AccessToken,
            request.WebhookUrl);

        var result = await _mediator.Send(command);

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

        return Ok(new { success = true, data = new { accountId = result.AccountId } });
    }

    /// <summary>
    /// EN: Get WhatsApp account by shop ID.
    /// VI: Lấy WhatsApp account theo shop ID.
    /// </summary>
    [HttpGet("shop/{shopId:guid}")]
    [ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetByShopId(Guid shopId)
    {
        var account = await _repository.GetByShopIdAsync(shopId);
        if (account == null)
        {
            return NotFound(new { success = false, error = "Account not found" });
        }

        return Ok(new
        {
            success = true,
            data = new
            {
                id = account.Id,
                shopId = account.ShopId,
                phoneNumberId = account.PhoneNumberId,
                status = account.Status.Name,
                messageTier = account.MessageTier,
                webhookUrl = account.WebhookUrl,
                createdAt = account.CreatedAt
            }
        });
    }

    /// <summary>
    /// EN: Disconnect WhatsApp account.
    /// VI: Ngắt kết nối WhatsApp account.
    /// </summary>
    [HttpDelete("{id:guid}")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> Disconnect(Guid id)
    {
        var account = await _repository.GetByIdAsync(id);
        if (account == null)
        {
            return NotFound(new { success = false, error = "Account not found" });
        }

        account.Disconnect();
        await _repository.UnitOfWork.SaveEntitiesAsync();

        return NoContent();
    }
}

public record ConnectAccountRequest(
    Guid ShopId,
    string PhoneNumberId,
    string AccessToken,
    string? WebhookUrl);
