﻿using AutoMapper;
using CleanMedApi.Data;
using CleanMedApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using CleanMedApi.Data.DTOs.ProfissionalDTOs;

namespace CleanMedApi.Controllers;

[ApiController]
[Route("api/v1")]
public class ProfissionalController : ControllerBase
{
    private CleanMedContext _context;
    private IMapper _mapper;

    public ProfissionalController(CleanMedContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    [HttpGet("profissionais")]
    [Authorize]
    public async Task<ActionResult<IEnumerable<Pessoa?>>> FindAll()
    {
        try
        {
            var profissionais = _context.Pessoas.Where(p => p.IsProfissional == true);

            return Ok(profissionais.ToArray());
        }
        catch (Exception ex)
        {
            BadRequestObjectResult badRequestObjectResult = BadRequest(new { Message = ex.InnerException.Message });

            return badRequestObjectResult;
        }
    }

    [HttpGet("profissional/{id}")]
    [Authorize]
    public async Task<ActionResult<ProfissionalReadDto?>> FindById(int Id)
    {
        try
        {

            Pessoa? profissional = _context.Pessoas.FirstOrDefault(p => p.Id == Id && p.IsProfissional == true);

            if (profissional is null)
            {
                return NotFound();
            }

            var profissionalReadDto = _mapper.Map<ProfissionalReadDto>(profissional);

            return Ok(profissionalReadDto);
        }
        catch (Exception ex)
        {
            BadRequestObjectResult badRequestObjectResult = BadRequest(new { Message = ex.InnerException });

            return badRequestObjectResult;
        }
    }    

    [HttpGet("profissionais/empresa/{id}")]
    [Authorize]
    public async Task<ActionResult<IEnumerable<Pessoa?>>> FindByIdEmpresa(int Id)
    {
        try
        {

            IEnumerable<Pessoa?> profissionais = _context
                .Pessoas.Where(p => p.IdEmpresa == Id && p.IsProfissional == true);

            return Ok(profissionais.ToArray());
        }
        catch (Exception ex)
        {
            BadRequestObjectResult badRequestObjectResult = BadRequest(new { Message = ex.InnerException });

            return badRequestObjectResult;
        }
    }

}