using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SolutionErp.Application.Forms;
using SolutionErp.Domain.Contracts;

namespace SolutionErp.Api.Controllers;

[ApiController]
[Route("api/forms")]
[Authorize]
public class FormsController(IMediator mediator) : ControllerBase
{
    [HttpGet("templates")]
    public async Task<ActionResult<List<ContractTemplateDto>>> List(
        [FromQuery] ContractType? type = null,
        [FromQuery] bool onlyActive = true,
        CancellationToken ct = default)
        => Ok(await mediator.Send(new ListContractTemplatesQuery(type, onlyActive), ct));

    [HttpGet("templates/{id:guid}")]
    public async Task<ActionResult<ContractTemplateDto>> Get(Guid id, CancellationToken ct)
        => Ok(await mediator.Send(new GetContractTemplateQuery(id), ct));

    [HttpPost("templates/{id:guid}/render")]
    public async Task<IActionResult> Render(Guid id, [FromBody] Dictionary<string, string?> data, CancellationToken ct)
    {
        var result = await mediator.Send(new RenderTemplateCommand(id, data), ct);
        return File(result.Content, result.ContentType, result.FileName);
    }

    [HttpPost("templates/{id:guid}/export-pdf")]
    public async Task<IActionResult> ExportPdf(Guid id, [FromBody] Dictionary<string, string?> data, CancellationToken ct)
    {
        var result = await mediator.Send(new ExportTemplatePdfCommand(id, data), ct);
        return File(result.Content, result.ContentType, result.FileName);
    }

    // ==================== Admin CRUD ====================

    // Upload new template — multipart form with file + metadata fields
    [HttpPost("templates")]
    [RequestSizeLimit(12_000_000)] // ~12 MB (validator caps at 10 MB)
    public async Task<ActionResult<ContractTemplateDto>> Upload(
        IFormFile file,
        [FromForm] string formCode,
        [FromForm] string name,
        [FromForm] ContractType? contractType = null,
        [FromForm] string? description = null,
        [FromForm] string? fieldSpec = null,
        CancellationToken ct = default)
    {
        if (file is null || file.Length == 0)
            return BadRequest(new { detail = "Chưa chọn file template." });

        await using var stream = file.OpenReadStream();
        var dto = await mediator.Send(new UploadContractTemplateCommand(
            formCode, name, contractType, description, fieldSpec,
            file.FileName, file.ContentType, file.Length, stream), ct);
        return Ok(dto);
    }

    [HttpPut("templates/{id:guid}")]
    public async Task<IActionResult> Update(Guid id, [FromBody] UpdateContractTemplateBody body, CancellationToken ct)
    {
        await mediator.Send(new UpdateContractTemplateCommand(
            id, body.Name, body.ContractType, body.Description, body.FieldSpec, body.IsActive), ct);
        return NoContent();
    }

    [HttpDelete("templates/{id:guid}")]
    public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
    {
        await mediator.Send(new DeleteContractTemplateCommand(id), ct);
        return NoContent();
    }
}

public record UpdateContractTemplateBody(
    string Name,
    ContractType? ContractType,
    string? Description,
    string? FieldSpec,
    bool IsActive);
