using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MktZaloService.API.Application.Commands.Customers;
using MktZaloService.API.Application.Queries.Customers;

namespace MktZaloService.API.Controllers;

/// <summary>
/// EN: Controller for managing customers.
/// VI: Controller để quản lý khách hàng.
/// </summary>
[ApiController]
[Route("api/v1/customers")]
[Authorize]
public class CustomersController : ControllerBase
{
    private readonly IMediator _mediator;

    public CustomersController(IMediator mediator)
    {
        _mediator = mediator;
    }

    /// <summary>
    /// EN: Get customer by ID.
    /// VI: Lấy khách hàng theo ID.
    /// </summary>
    [HttpGet("{id:guid}")]
    public async Task<ActionResult<CustomerDto>> GetCustomer(
        Guid id,
        CancellationToken ct = default)
    {
        var query = new GetCustomerQuery(id);
        var result = await _mediator.Send(query, ct);

        if (result == null)
        {
            return NotFound(new { error = "Customer not found" });
        }

        return Ok(result);
    }

    /// <summary>
    /// EN: Get customer by Zalo user ID.
    /// VI: Lấy khách hàng theo Zalo user ID.
    /// </summary>
    [HttpGet("by-zalo/{zaloUserId}")]
    public async Task<ActionResult<CustomerDto>> GetCustomerByZaloId(
        string zaloUserId,
        CancellationToken ct = default)
    {
        var query = new GetCustomerByZaloIdQuery(zaloUserId);
        var result = await _mediator.Send(query, ct);

        if (result == null)
        {
            return NotFound(new { error = "Customer not found" });
        }

        return Ok(result);
    }

    /// <summary>
    /// EN: Update customer profile and tags.
    /// VI: Cập nhật profile và tags khách hàng.
    /// </summary>
    [HttpPatch("{id:guid}")]
    public async Task<IActionResult> UpdateCustomer(
        Guid id,
        [FromBody] UpdateCustomerRequest request,
        CancellationToken ct = default)
    {
        var command = new UpdateCustomerCommand(
            id,
            request.DisplayName,
            request.AvatarUrl,
            request.PhoneNumber,
            request.Email,
            request.TagsToAdd,
            request.TagsToRemove);

        var result = await _mediator.Send(command, ct);

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

        return NoContent();
    }
}

/// <summary>
/// EN: Request to update customer.
/// VI: Request để cập nhật khách hàng.
/// </summary>
public record UpdateCustomerRequest(
    string? DisplayName,
    string? AvatarUrl,
    string? PhoneNumber,
    string? Email,
    List<string>? TagsToAdd,
    List<string>? TagsToRemove
);
