using AdsBillingService.API.Application.Queries;
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace AdsBillingService.API.Controllers;

/// <summary>
/// EN: API Controller for managing invoices.
/// VI: API Controller quản lý hóa đơn.
/// </summary>
[ApiController]
[Route("api/v1/ads-billing/invoices")]
[Produces("application/json")]
public class InvoicesController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<InvoicesController> _logger;

    public InvoicesController(IMediator mediator, ILogger<InvoicesController> logger)
    {
        _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    /// <summary>
    /// EN: Get list of invoices with optional filtering.
    /// VI: Lấy danh sách hóa đơn với bộ lọc tùy chọn.
    /// </summary>
    [HttpGet]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task<IActionResult> GetInvoices(
        [FromQuery] Guid? billingAccountId = null,
        [FromQuery] string? status = null,
        [FromQuery] int pageNumber = 1,
        [FromQuery] int pageSize = 20)
    {
        _logger.LogInformation("Getting invoices with filters: AccountId={AccountId}, Status={Status}, Page={Page}", 
            billingAccountId, status, pageNumber);

        var query = new GetInvoicesQuery(billingAccountId, status, pageNumber, pageSize);
        var invoices = await _mediator.Send(query);

        return Ok(new 
        { 
            pageNumber,
            pageSize,
            total = invoices.Count,
            data = invoices
        });
    }

    /// <summary>
    /// EN: Get invoice details by ID.
    /// VI: Lấy chi tiết hóa đơn theo ID.
    /// </summary>
    [HttpGet("{id}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetInvoiceById(Guid id)
    {
        _logger.LogInformation("Getting invoice {InvoiceId}", id);

        var query = new GetInvoiceByIdQuery(id);
        var invoice = await _mediator.Send(query);

        if (invoice == null)
        {
            return NotFound(new { message = $"Invoice {id} not found" });
        }

        return Ok(invoice);
    }

    /// <summary>
    /// EN: Download invoice as PDF (placeholder).
    /// VI: Tải hóa đơn dạng PDF (placeholder).
    /// </summary>
    [HttpGet("{id}/download")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> DownloadInvoice(Guid id)
    {
        _logger.LogInformation("Downloading invoice {InvoiceId}", id);

        // EN: Verify invoice exists / VI: Xác minh hóa đơn tồn tại
        var query = new GetInvoiceByIdQuery(id);
        var invoice = await _mediator.Send(query);

        if (invoice == null)
        {
            return NotFound(new { message = $"Invoice {id} not found" });
        }

        // TODO: Generate PDF using a PDF library
        // EN: For now, return invoice data as JSON / VI: Tạm thời trả về dữ liệu JSON
        return Ok(new 
        { 
            message = "PDF generation not yet implemented",
            invoice = invoice
        });
    }
}
