using BusinessLayer.IRepository;
using BusinessLayer.Repository;
using DataAccess.DAOs;
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 SubjectCategoryController : ControllerBase
    {
        private ISubjectCategoryRepository _subjectCategoryRepository;

        public SubjectCategoryController(ISubjectCategoryRepository subjectCategoryRepository)
        {
            _subjectCategoryRepository = subjectCategoryRepository;
        }

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

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

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

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

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

        [HttpDelete]
        [Authorize(AuthenticationSchemes = "Bearer", Roles = "0")]
        public void Delete(int id)
        {
            _subjectCategoryRepository.Delete(id);
        }
        private bool Exist(SubjectCategoryDTO subjectCategory)
        {
            var item = _subjectCategoryRepository.GetByName(subjectCategory.CategoryId, subjectCategory.CategoryName);
            return item != null;
        }
    }
}
