using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PokemonSleepAPI.Data;
using PokemonSleepAPI.Models;
using PokemonSleepAPI.Models.Dto;
using System;

namespace PokemonSleepAPI.Controllers
{
    [Route("api/pokemon")]
    [ApiController]
    public class PokemonController : ControllerBase
    {
        private readonly PokemonDbContext _db;
        private ResponseDto _response;
        private IMapper _mapper;

        public PokemonController(PokemonDbContext db, IMapper mapper)
        {
            _db = db;
            _mapper = mapper;
            _response = new ResponseDto();
        }

        /* Get all Pokemon */
        [HttpGet]
        public ResponseDto GetAllPokemon()
        {
            try
            {
                IEnumerable<Pokemon> objList = _db.Pokemons.ToList();
                _response.Message = "Pokemons found.";
                _response.Result = _mapper.Map<IEnumerable<PokemonDto>>(objList);

            }
            catch (Exception ex)
            {
                _response.IsSuccess = false;
                _response.Message = ex.Message;
            }
            return _response;
        }
        /* Get Pokemon by Id */
        [HttpGet]
        [Route("{id:int}")]
        public ResponseDto GetPokemonById(int id)
        {
            try
            {
                Pokemon pokemon = _db.Pokemons.FirstOrDefault(p => p.Id == id);
                _response.Message = $"{pokemon.Name} found.";
                _response.Result = _mapper.Map<PokemonDto>(pokemon);

            }
            catch (Exception ex)
            {
                _response.IsSuccess = false;
                _response.Message = ex.Message;
            }
            return _response;
        }

        [HttpPost]
        public ResponseDto PostPokemon([FromBody] PokemonDto pokemonDto) {
            try
            {
                Pokemon pokemon = _mapper.Map<Pokemon>(pokemonDto);
                _db.Pokemons.Add(pokemon);
                _db.SaveChanges();

                _response.Result = _mapper.Map<PokemonDto>(pokemon);

            }
            catch (Exception ex)
            {
                _response.IsSuccess = false;
                _response.Message = ex.Message;
            }
            return _response;
        }

        [HttpDelete]
        public ResponseDto DeletePokemon(int id)
        {
            try
            {
                Pokemon pokemon = _db.Pokemons.First(p => p.Id == id);
                _db.Pokemons.Remove(pokemon);
                _db.SaveChanges();
            }
            catch (Exception ex)
            {
                _response.IsSuccess = false;
                _response.Message = ex.Message;
            }
            return _response;
        }

    }
}
