using adas_core.Application.Exceptions;
using adas_core.Application.Services.Interfaces;
using adas_core.Authentication.Attributes;
using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.DTO;
using adas_core.Domain.Models.Filter;
using adas_core.Logging;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;

namespace adas_core.Controllers;

[Route("treatments")]
[ApiController]
public class TreatmentsController : ControllerBase
{
    private readonly IPatientService _patientService;
    private readonly ITreatmentService _treatmentService;

    public TreatmentsController(ITreatmentService treatmentService, IPatientService patientService)
    {
        LogExecutionContext.TrySetTraceIdentifier(Guid.NewGuid().ToString(), true);

        _treatmentService = treatmentService;
        _patientService = patientService;
    }


    [HttpPost]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthSome)]
    [PermissionAuthorize("Source", "DisplayId")]
    public async Task<IActionResult> ProcessRequest([FromBody] TreatmentDto treatmentDto)
    {
        var request = new ApiRequest
        {
            TraceId = Guid.NewGuid().ToString(),
            Type = "RAS_O17",
            PatientNumber = treatmentDto.PatientNumber,
            Location = treatmentDto.Location,
            MessageTime = treatmentDto.MessageTime,
            WaitResult = treatmentDto.WaitResult,
            RequestFromPanel = true,
            Treatments = []
        };


        if (treatmentDto.Treatment != null)
            request.Treatments.Add(treatmentDto.Treatment);

        var patient = await _patientService.FindByPatientNumber(treatmentDto.PatientNumber, true) ??
                      throw new NotFoundException(HttpEnum.ErrorMessage.NotFoundResourceMissing);

        request.Location ??= patient.Location;

        await _treatmentService.SaveRequestAsync(request);

        //var treatList = await _treatmentService.GetTreatmentsByPatientId(patient.Id);

        //if (!treatList.Any(t => t.MessageTime == treatmentDto.MessageTime))
        //{
        //    return NotFound($"Treatment not inserted");
        //}

        //var treat = treatList.FirstOrDefault(t => t.MessageTime == treatmentDto.MessageTime);
        //if (treat == null)
        //{
        //    return BadRequest("Error inserting treatment");
        //}

        //return Ok(treat);

        return Ok();
    }

    [HttpGet("{patientid}/patient-id")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthSome)]
    [PermissionAuthorize("Source", "DisplayId")]
    public async Task<IActionResult> GetTreatmentsByPatientId(string patientid)
    {
        if (!ObjectId.TryParse(patientid, out var validId))
            throw new BadRequestException(HttpEnum.ErrorMessage.BadRequestInvalidFormat);
        var treatments = await _treatmentService.GetTreatmentsByPatientId(validId);
        return Ok(treatments.OrderBy(p => p.OrderTime).Take(50));
    }


    [HttpPut]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthSome)]
    [PermissionAuthorize("Source", "DisplayId")]
    public async Task<IActionResult> UpdateTreatment([FromBody] PatientTreatment request)
    {
        var treatment = await _treatmentService.UpdateTreatment(request);
        return Ok(treatment);
    }

    //Archive

    [HttpDelete("{patientid}/patient-id")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthSome)]
    [PermissionAuthorize("Source", "DisplayId")]
    public async Task<IActionResult> DeleteTreatment(string patientId)
    {
        if (!ObjectId.TryParse(patientId, out var id))
            throw new BadRequestException(HttpEnum.ErrorMessage.BadRequestInvalidFormat);
        await _treatmentService.DeleteByPatientId(id);
        return Ok();
    }

    [HttpDelete("{treatmentId}")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthSome)]
    [PermissionAuthorize("Source", "DisplayId")]
    public async Task<IActionResult> DeleteTreatmentById(string treatmentId)
    {
        if (!ObjectId.TryParse(treatmentId, out var id))
            throw new BadRequestException(HttpEnum.ErrorMessage.BadRequestInvalidFormat);

        await _treatmentService.DeleteById(id);
        return Ok();
    }

    [HttpPost("paginated")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthSome)]
    [PermissionAuthorize("Source", "DisplayId")]
    public async Task<IActionResult> GetPaginatedTreatments([FromBody] PaginationFilter request)
    {
        if (request == null) throw new BadRequestException(HttpEnum.ErrorMessage.BadRequestMissingParameters);
        var treatments = await _treatmentService.GetPaginatedTreatments(request);

        return Ok(treatments);
    }
}