using System.Globalization;
using ApiDenuncias.Services;
using GestionaDenuncias.Shared.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ApiDenuncias.Controllers;

[ApiController]
[Authorize]
[Route("api/configuration")]
public sealed class ConfigurationController : ControllerBase
{
    private readonly AppConfigurationService _configurationService;

    public ConfigurationController(AppConfigurationService configurationService)
    {
        _configurationService = configurationService;
    }

    [HttpGet]
    public async Task<ActionResult<AppConfigurationDto>> Get(CancellationToken cancellationToken)
    {
        return Ok(await _configurationService.GetAsync(cancellationToken));
    }

    [HttpPut("external-update-cutoff")]
    [Authorize(Policy = "ConfigurationAdministrators")]
    public async Task<ActionResult<AppConfigurationDto>> SetExternalUpdateCutoff(
        UpdateExternalUpdateCutoffRequest request,
        CancellationToken cancellationToken)
    {
        DateOnly? date = null;
        if (!string.IsNullOrWhiteSpace(request.Date))
        {
            if (!DateOnly.TryParseExact(
                request.Date.Trim(),
                ["yyyy-MM-dd", "dd/MM/yyyy"],
                CultureInfo.InvariantCulture,
                DateTimeStyles.None,
                out var parsed))
            {
                return BadRequest(new ApiError("Debes indicar una fecha valida con formato YYYY-MM-DD o DD/MM/AAAA."));
            }

            date = parsed;
        }

        return Ok(await _configurationService.SetExternalUpdateCutoffDateAsync(date, cancellationToken));
    }
}
