using Dto.Classe;
using Dto.Factories;
using Interface;
using Microsoft.AspNetCore.Mvc;
using Modele.Classe;

namespace Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class Pilotes : Controller
    {
        private readonly IApi data;

        public Pilotes(IApi manager)
        {
            this.data = manager;
        }


        [HttpGet]
        public async Task<IActionResult> Get(string? pseudo)
        {

            if (pseudo == null)
            {
                return Ok((await data.GetPilotes()).Select(e => e.ModeleToDTO()));
            }
            else
            {
                Pilote pilote = await data.GetOnePilote(pseudo);
                if (pilote == null)
                {
                    return BadRequest(pseudo);
                }
                else
                {
                    return Ok(pilote.ModeleToDTO());
                }
            }
        }

        [HttpPost]
        public async Task<IActionResult> Post(string Email,string password,PiloteDTO piloteDTO)
        {
            Pilote piloteCheck = await data.CheckPilote(Email, password);
            if (piloteCheck == null)
            {
                return BadRequest();
            }

            Pilote pilote = await data.AddPilote(piloteDTO.DTOToModele());

            if (pilote == null)
            {
                return BadRequest("Le pilote existe déjà !");
            }
            return Ok(pilote.ModeleToDTO());
        }

        [HttpGet("check")]
        public async Task<IActionResult> CheckPilote(string Email,string password)
        {
            Pilote pilote = await data.CheckPilote(Email, password);
            if ( pilote == null)
            {
                return BadRequest(null);
            }
            return Ok(pilote);
        }
    }
}
