using BusinessLayer.IRepository;
using BusinessLayer.Repository;
using DataAccess.DTOs;
using DataAccess.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using System.Data;

namespace API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class QuestionCategoryController : ControllerBase
    {
        private IQuestionCategoryRepository _questionCategoryRepository;

        public QuestionCategoryController(IQuestionCategoryRepository questionCategoryRepository)
        {
            _questionCategoryRepository = questionCategoryRepository;
        }

        [HttpGet]
        [EnableQuery]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public IActionResult Get(int? status)
        {
            return Ok(_questionCategoryRepository.GetAll(status));
        }

        [HttpGet("Id")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public IActionResult Get(int id, int? status)
        {
            return Ok(_questionCategoryRepository.GetById(id, status));
        }

        [HttpPost]
        [Authorize(AuthenticationSchemes = "Bearer", Roles = "0")]
        public void Post([FromBody] QuestionCategoryDTO questionCategoryDTO)
        {
            if(Exist(questionCategoryDTO))
            {
                return;
            }
            _questionCategoryRepository.Add(questionCategoryDTO);
        }

        [HttpPut]
        [Authorize(AuthenticationSchemes = "Bearer", Roles = "0")]
        public void Put([FromBody] QuestionCategoryDTO questionCategoryDTO)
        {
            if (Exist(questionCategoryDTO))
            {
                return;
            }
            _questionCategoryRepository.Update(questionCategoryDTO);
        }

        [HttpDelete]
        [Authorize(AuthenticationSchemes = "Bearer", Roles = "0")]
        public void Delete(int id)
        {
            _questionCategoryRepository.Delete(id);
        }

        private bool Exist(QuestionCategoryDTO questionCategoryDTO)
        {
            var item = _questionCategoryRepository.GetByName(questionCategoryDTO.CategoryId, questionCategoryDTO.CategoryName);
            return item != null;
        }
    }
}
