using Apollinare.API.Services;
using Apollinare.Domain.Entities;
using Apollinare.Domain.Enums;
using Microsoft.AspNetCore.Mvc;

namespace Apollinare.API.Controllers;

[ApiController]
[Route("api/custom-fields")]
public class CustomFieldDefinitionsController : ControllerBase
{
    private readonly CustomFieldService _service;
    private readonly ILogger<CustomFieldDefinitionsController> _logger;

    public CustomFieldDefinitionsController(CustomFieldService service, ILogger<CustomFieldDefinitionsController> logger)
    {
        _service = service;
        _logger = logger;
    }

    [HttpGet]
    public async Task<ActionResult<List<CustomFieldDefinitionDto>>> GetAll()
    {
        var defs = await _service.GetAllDefinitionsAsync();
        return Ok(defs.Select(ToDto).ToList());
    }

    [HttpGet("entity/{entityName}")]
    public async Task<ActionResult<List<CustomFieldDefinitionDto>>> GetByEntity(string entityName)
    {
        var defs = await _service.GetDefinitionsByEntityAsync(entityName);
        return Ok(defs.Select(ToDto).ToList());
    }

    [HttpGet("{id:int}")]
    public async Task<ActionResult<CustomFieldDefinitionDto>> Get(int id)
    {
        var def = await _service.GetDefinitionAsync(id);
        if (def == null) return NotFound();
        return Ok(ToDto(def));
    }

    [HttpPost]
    public async Task<ActionResult<CustomFieldDefinitionDto>> Create(CustomFieldDefinitionDto dto)
    {
        try
        {
            var entity = new CustomFieldDefinition
            {
                EntityName = dto.EntityName,
                FieldName = dto.FieldName,
                Label = dto.Label,
                Type = dto.Type,
                IsRequired = dto.IsRequired,
                DefaultValue = dto.DefaultValue,
                OptionsJson = dto.OptionsJson,
                SortOrder = dto.SortOrder,
                Description = dto.Description,
                IsActive = dto.IsActive,
                ValidationRegex = dto.ValidationRegex,
                Placeholder = dto.Placeholder
            };

            var created = await _service.CreateDefinitionAsync(entity);
            return CreatedAtAction(nameof(Get), new { id = created.Id }, ToDto(created));
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { error = ex.Message });
        }
    }

    [HttpPut("{id:int}")]
    public async Task<ActionResult<CustomFieldDefinitionDto>> Update(int id, CustomFieldDefinitionDto dto)
    {
        try
        {
            var entity = new CustomFieldDefinition
            {
                EntityName = dto.EntityName,
                FieldName = dto.FieldName,
                Label = dto.Label,
                Type = dto.Type,
                IsRequired = dto.IsRequired,
                DefaultValue = dto.DefaultValue,
                OptionsJson = dto.OptionsJson,
                SortOrder = dto.SortOrder,
                Description = dto.Description,
                IsActive = dto.IsActive,
                ValidationRegex = dto.ValidationRegex,
                Placeholder = dto.Placeholder
            };

            var updated = await _service.UpdateDefinitionAsync(id, entity);
            return Ok(ToDto(updated));
        }
        catch (KeyNotFoundException)
        {
            return NotFound();
        }
    }

    [HttpDelete("{id:int}")]
    public async Task<ActionResult> Delete(int id)
    {
        try
        {
            await _service.DeleteDefinitionAsync(id);
            return NoContent();
        }
        catch (KeyNotFoundException)
        {
            return NotFound();
        }
    }

    private static CustomFieldDefinitionDto ToDto(CustomFieldDefinition entity)
    {
        return new CustomFieldDefinitionDto
        {
            Id = entity.Id,
            EntityName = entity.EntityName,
            FieldName = entity.FieldName,
            Label = entity.Label,
            Type = entity.Type,
            IsRequired = entity.IsRequired,
            DefaultValue = entity.DefaultValue,
            OptionsJson = entity.OptionsJson,
            SortOrder = entity.SortOrder,
            Description = entity.Description,
            IsActive = entity.IsActive,
            ValidationRegex = entity.ValidationRegex,
            Placeholder = entity.Placeholder
        };
    }
}

public class CustomFieldDefinitionDto
{
    public int Id { get; set; }
    public required string EntityName { get; set; }
    public required string FieldName { get; set; }
    public required string Label { get; set; }
    public CustomFieldType Type { get; set; }
    public bool IsRequired { get; set; }
    public string? DefaultValue { get; set; }
    public string? OptionsJson { get; set; }
    public int SortOrder { get; set; }
    public string? Description { get; set; }
    public bool IsActive { get; set; }
    public string? ValidationRegex { get; set; }
    public string? Placeholder { get; set; }
}
