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

namespace API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class QuestionController : ControllerBase
    {
        private IQuestionRepository _questionRepository;

        public QuestionController(IQuestionRepository questionRepository)
        {
            _questionRepository = questionRepository;
        }

        [HttpGet]
        [EnableQuery]
        [Authorize(AuthenticationSchemes = "Bearer", Roles = "1")]
        public IActionResult Get()
        {
            return Ok(_questionRepository.GetAll());
        }

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

        [HttpPost]
        [Authorize(AuthenticationSchemes = "Bearer", Roles = "1")]
        public void Post([FromBody] QuestionRequestDTO questionDTO)
        {
            if (Exist(questionDTO))
            {
                return;
            }
            _questionRepository.Add(questionDTO);
        }

        [HttpPut]
        [Authorize(AuthenticationSchemes = "Bearer", Roles = "1")]
        public void Put([FromBody] QuestionRequestDTO questionDTO)
        {
            _questionRepository.Update(questionDTO);
        }

        [HttpDelete]
        [Authorize(AuthenticationSchemes = "Bearer", Roles = "1")]
        public void Delete(int id)
        {
            _questionRepository.Delete(id);
        }
        private bool Exist(QuestionRequestDTO questionRequestDTO)
        {
            var item = _questionRepository.GetByContent(questionRequestDTO.QuestionId, questionRequestDTO.Content);
            return item != null;
        }
    }
}
