using Application.Endpoints.MedicalHistories;
using Application.Services.Database;
using Core.Entities;
using Microsoft.AspNetCore.Mvc;

namespace HealthcareManager.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class MedicalHistoryController : ControllerBase
{
    private readonly IMedicalHistoryRepository _medicalHistoryRepository;
    private readonly IPacientRepository _pacientRepository;

    public MedicalHistoryController(IMedicalHistoryRepository medicalHistoryRepository, IPacientRepository pacientRepository)
    {
        _medicalHistoryRepository = medicalHistoryRepository ?? throw new ArgumentNullException(nameof(medicalHistoryRepository));
        _pacientRepository = pacientRepository ?? throw new ArgumentNullException(nameof(pacientRepository));
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<MedicalHistory>> GetAsync(Guid id)
    {
        var handler = new MedicalHistoryHandler(_medicalHistoryRepository, _pacientRepository);
        var response = await handler.HandleGet(id);
        if (!response.Success)
        {
            return BadRequest(response);
        }

        return Ok(response.Data);
    }

    [HttpPost("{id}")]
    public async Task<ActionResult<MedicalHistory>> PostAsync(Guid id, [FromBody] byte[] description)
    {
        var handler = new MedicalHistoryHandler(_medicalHistoryRepository, _pacientRepository);
        var response = await handler.HandleCreate(id, description).ConfigureAwait(false);

        if (!response.Success)
        {
            return Unauthorized(response);
        }

        return Ok(response);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> UpdateAsync(Guid id, [FromBody] MedicalHistoryDTO medicalHistoryDTO)
    {
        var handler = new MedicalHistoryHandler(_medicalHistoryRepository, _pacientRepository);
        var response = await handler.HandleUpdate(id, medicalHistoryDTO).ConfigureAwait(false);

        if (response.Success)
        {
            return Ok(response);
        }

        return BadRequest(response);
    }

    [HttpPut("grant_access")]
    public async Task<IActionResult> GrantAccessToMedicalHistory(Guid id)
    {
        return NotFound();
    }
}
