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

namespace MktXService.API.Controllers;

/// <summary>
/// EN: Controller for Contact management.
/// VI: Controller quản lý liên hệ.
/// </summary>
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[Produces("application/json")]
[Authorize]
public class ContactsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<ContactsController> _logger;

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

    /// <summary>
    /// EN: Get all contacts for an account.
    /// VI: Lấy tất cả liên hệ của tài khoản.
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(IEnumerable<ContactDto>), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetContacts(
        [FromQuery] Guid accountId,
        [FromQuery] string? search = null,
        [FromQuery] List<string>? tags = null,
        [FromQuery] int skip = 0,
        [FromQuery] int take = 20)
    {
        var contacts = await _mediator.Send(new GetContactsQuery(accountId, search, tags, skip, take));
        return Ok(new { success = true, data = contacts });
    }

    /// <summary>
    /// EN: Get a contact by ID.
    /// VI: Lấy liên hệ theo ID.
    /// </summary>
    [HttpGet("{id:guid}")]
    [ProducesResponseType(typeof(ContactDetailDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetContact(Guid id)
    {
        var contact = await _mediator.Send(new GetContactQuery(id));
        if (contact == null)
            return NotFound(new { success = false, error = new { code = "CONTACT_NOT_FOUND", message = $"Contact {id} not found" } });

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