using Butter.Dtos.Settings;
using Butter.Types;
using Lactose.Mapper;
using Lactose.Models;
using Lactose.Repositories;
using Lactose.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Lactose.Controllers;

[ApiController]
[Authorize(Roles = "Admin")]
[Route("api/[controller]")]
public class SettingsController(
    //TODO: Add logging
    //ILogger<SettingsController> logger,
    LactoseAuthService authService,
    ISettingsRepository settingsRepository
) : ControllerBase {
    [HttpPut]
    [Authorize(Roles = "Admin")]
    public ActionResult Create([FromBody] SettingDto settingDto) {
        var accessLevel = authService.GetUserData(User)?.AccessLevel ?? EAccessLevel.User;
        if (accessLevel != EAccessLevel.Admin) { return Unauthorized(); }
        
        settingsRepository.Create(new Setting {
                Name  = settingDto.Name,
                Value = settingDto.Value
            });
        return Ok();
    }

    [HttpGet]
    [Authorize(Roles = "Admin")]
    public ActionResult<SettingDto> Get() {
        var accessLevel = authService.GetUserData(User)?.AccessLevel ?? EAccessLevel.User;
        if (accessLevel != EAccessLevel.Admin) return Unauthorized();
        
        return Ok(settingsRepository.Get().ToSettingsDto());
    }
    
    [HttpGet]
    [Authorize(Roles = "Admin")]
    [Route("get-all")]
    public ActionResult<SettingsDto> GetAll() {
        var accessLevel = authService.GetUserData(User)?.AccessLevel ?? EAccessLevel.User;
        if (accessLevel != EAccessLevel.Admin) return Unauthorized();
        
        return Ok(settingsRepository.Get().ToSettingsDto());
    }

    [HttpPost]
    [Authorize(Roles = "Admin")]
    public ActionResult Update([FromBody] SettingDto settingDto) {
        var accessLevel = authService.GetUserData(User)?.AccessLevel ?? EAccessLevel.User;
        if (accessLevel != EAccessLevel.Admin) return Unauthorized();
        
        settingsRepository.Update(settingDto.ToSetting());
        return Ok();
    }

    [HttpDelete]
    [Authorize(Roles = "Admin")]
    public ActionResult Delete([FromBody] SettingDto settingDto) {
        var accessLevel = authService.GetUserData(User)?.AccessLevel ?? EAccessLevel.User;
        if (accessLevel != EAccessLevel.Admin) return Unauthorized();

        settingsRepository.Delete(settingDto.ToSetting());
        return Ok();
    }
    
    [HttpPost]
    [Authorize(Roles = "Admin")]
    [Route("delete-all")]
    public ActionResult DeleteAll() {
        var accessLevel = authService.GetUserData(User)?.AccessLevel ?? EAccessLevel.User;
        if (accessLevel != EAccessLevel.Admin) return Unauthorized();

        settingsRepository.Delete();
        return Ok();
    }
}