using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using WhatsAppService.Domain.AggregatesModel.CustomerAggregate;

namespace WhatsAppService.API.Controllers;

/// <summary>
/// EN: Controller for managing customers.
/// VI: Controller để quản lý khách hàng.
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Produces("application/json")]
[Authorize]
public class CustomersController : ControllerBase
{
    private readonly ICustomerRepository _repository;
    private readonly ILogger<CustomersController> _logger;

    public CustomersController(
        ICustomerRepository repository,
        ILogger<CustomersController> logger)
    {
        _repository = repository;
        _logger = logger;
    }

    /// <summary>
    /// EN: Get customers by shop with pagination.
    /// VI: Lấy khách hàng theo shop với phân trang.
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetCustomers(
        [FromQuery] Guid shopId,
        [FromQuery] int skip = 0,
        [FromQuery] int take = 20)
    {
        var customers = await _repository.GetByShopIdAsync(shopId, skip, take);
        
        return Ok(new
        {
            success = true,
            data = customers.Select(c => new
            {
                id = c.Id,
                waId = c.WaId,
                name = c.Name,
                profilePictureUrl = c.ProfilePictureUrl,
                optInStatus = c.Consent.Status,
                tags = c.Tags,
                firstContactedAt = c.FirstContactedAt,
                createdAt = c.CreatedAt
            })
        });
    }

    /// <summary>
    /// EN: Get customer by ID.
    /// VI: Lấy khách hàng theo ID.
    /// </summary>
    [HttpGet("{id:guid}")]
    [ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetById(Guid id)
    {
        var customer = await _repository.GetByIdAsync(id);
        if (customer == null)
        {
            return NotFound(new { success = false, error = "Customer not found" });
        }

        return Ok(new
        {
            success = true,
            data = new
            {
                id = customer.Id,
                waId = customer.WaId,
                name = customer.Name,
                profilePictureUrl = customer.ProfilePictureUrl,
                optInStatus = customer.Consent.Status,
                optInTimestamp = customer.Consent.Timestamp,
                optInSource = customer.Consent.Source,
                tags = customer.Tags,
                customFields = customer.CustomFields,
                firstContactedAt = customer.FirstContactedAt,
                createdAt = customer.CreatedAt
            }
        });
    }

    /// <summary>
    /// EN: Update customer profile.
    /// VI: Cập nhật hồ sơ khách hàng.
    /// </summary>
    [HttpPatch("{id:guid}")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> Update(Guid id, [FromBody] UpdateCustomerRequest request)
    {
        var customer = await _repository.GetByIdAsync(id);
        if (customer == null)
        {
            return NotFound(new { success = false, error = "Customer not found" });
        }

        if (!string.IsNullOrEmpty(request.Name))
        {
            customer.UpdateName(request.Name);
        }

        if (request.Tags != null)
        {
            // Clear and re-add tags
            foreach (var tag in customer.Tags.ToList())
            {
                customer.RemoveTag(tag);
            }
            foreach (var tag in request.Tags)
            {
                customer.AddTag(tag);
            }
        }

        if (request.CustomFields != null)
        {
            foreach (var field in request.CustomFields)
            {
                customer.UpdateCustomField(field.Key, field.Value);
            }
        }

        await _repository.UnitOfWork.SaveEntitiesAsync();
        return NoContent();
    }

    /// <summary>
    /// EN: Update customer opt-in consent.
    /// VI: Cập nhật đồng ý opt-in của khách hàng.
    /// </summary>
    [HttpPost("{id:guid}/consent")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> UpdateConsent(Guid id, [FromBody] UpdateConsentRequest request)
    {
        var customer = await _repository.GetByIdAsync(id);
        if (customer == null)
        {
            return NotFound(new { success = false, error = "Customer not found" });
        }

        if (request.OptIn)
        {
            customer.UpdateOptIn("opted_in", request.Source ?? "api");
        }
        else
        {
            customer.UpdateOptIn("opted_out", request.Source ?? "api");
        }

        await _repository.UnitOfWork.SaveEntitiesAsync();
        return NoContent();
    }
}

public record UpdateCustomerRequest(
    string? Name,
    List<string>? Tags,
    Dictionary<string, string>? CustomFields);

public record UpdateConsentRequest(
    bool OptIn,
    string? Source);
