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

namespace API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SubjectController : ControllerBase
    {
        private ISubjectRepository _subjectRepository;

        public SubjectController(ISubjectRepository subjectRepository)
        {
            _subjectRepository = subjectRepository;
        }

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

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

        [HttpGet("Name")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public IActionResult Get(string name)
        {
            return Ok(_subjectRepository.GetByName(name));
        }

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

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

        [HttpDelete]
        [Authorize(AuthenticationSchemes = "Bearer", Roles = "0")]
        public void Delete(int id)
        {
            _subjectRepository.Delete(id);
        }
        private bool Exist(SubjectRequestDTO subjectRequestDTO)
        {
            var item = _subjectRepository.GetByName(subjectRequestDTO.SubjectId, subjectRequestDTO.SubjectName);
            return item != null;
        }
    }
}
