using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Authorize]
public class EncountersController : ControllerBase
{
    private readonly IEncounterReadService _encounters;

    public EncountersController(IEncounterReadService encounters) => _encounters = encounters;

    [HttpGet("api/v1/encounters")]
    public async Task<IActionResult> List(
        [FromQuery] string? status,
        [FromQuery] string? department)
    {
        if (status is not null and not "ACTIVE")
            return BadRequest(ApiResponse<object>.Fail(400, "Gateway supports ACTIVE only.", "INVALID_STATUS"));

        if (!string.IsNullOrEmpty(department) && !TryParseDepartment(department, out _))
            return BadRequest(ApiResponse<object>.Fail(400, "Invalid department filter.", "INVALID_DEPARTMENT"));

        var items = await _encounters.ListActiveAsync(department);
        return Ok(ApiResponse<object>.Ok(new { items }));
    }

    [HttpGet("api/v1/encounters/{id:guid}")]
    public async Task<IActionResult> Get(Guid id)
    {
        var detail = await _encounters.GetByIdAsync(id);
        if (detail is null)
            return NotFound(ApiResponse<object>.Fail(404, "Encounter not found.", "ENCOUNTER_NOT_FOUND"));

        return Ok(ApiResponse<EncounterDetail>.Ok(detail));
    }

    private static bool TryParseDepartment(string department, out Department _)
    {
        try
        {
            _ = DepartmentExtensions.FromDbString(department);
            return true;
        }
        catch (ArgumentOutOfRangeException)
        {
            _ = default;
            return false;
        }
    }
}
