using Butter.Dtos.Folder;
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 FolderController(
    //TODO: add logging
    //ILogger<FolderController> logger,
    LactoseAuthService authService,
    IFolderRepository folderRepository
) : ControllerBase {
    [HttpPut]
    [Authorize(Roles = "Admin")]
    public ActionResult Create([FromBody] FolderCreateDto folderCreateDto) {
        var accessLevel = authService.GetUserData(User)?.AccessLevel ?? EAccessLevel.User;

        if (accessLevel != EAccessLevel.Admin) { return Unauthorized(); }

        Folder newFolder = new Folder {
            BasePath = folderCreateDto.BasePath,
            Active   = false
        };

        folderRepository.Create(newFolder);
        return Ok();
    }

    [HttpGet]
    [Authorize(Roles = "Admin")]
    public ActionResult<List<FolderFullDto>> GetAll() {
        var accessLevel = authService.GetUserData(User)?.AccessLevel ?? EAccessLevel.User;

        if (accessLevel != EAccessLevel.Admin) { return Unauthorized(); }
        return Ok(
            folderRepository.GetAll()
                .Select(folder => folder.ToFolderDto())
                .ToList()
            );
    }
    
    [HttpGet("{id}")]
    [Authorize(Roles = "Admin")]
    public ActionResult<FolderFullDto> Get([FromRoute] Guid id) {
        var accessLevel = authService.GetUserData(User)?.AccessLevel ?? EAccessLevel.User;

        if (accessLevel != EAccessLevel.Admin) { return Unauthorized(); }

        var folder = folderRepository.Get(id);

        if (folder == null) return NotFound();
        
        return Ok(folder.ToFolderDto());
    }

    [HttpPost("{id}")]
    [Authorize(Roles = "Admin")]
    public ActionResult Update([FromRoute] Guid id, [FromBody] FolderUpdateDto folderUpdateDto) {
        var accessLevel = authService.GetUserData(User)?.AccessLevel ?? EAccessLevel.User;

        if (accessLevel != EAccessLevel.Admin) { return Unauthorized(); }

        Folder? folder = folderRepository.Get(id);
        if (folder == null) return NotFound();
        
        folder.BasePath = folderUpdateDto.BasePath ?? folder.BasePath;
        folder.Active   = folderUpdateDto.Active ?? folder.Active;

        folderRepository.Update(id, folder);
        return Ok();
    }

    [HttpDelete("{id}")]
    [Authorize(Roles = "Admin")]
    public ActionResult Delete([FromRoute] Guid id) {
        var accessLevel = authService.GetUserData(User)?.AccessLevel ?? EAccessLevel.User;

        if (accessLevel != EAccessLevel.Admin) { return Unauthorized(); }

        folderRepository.Delete(id);
        return Ok();
    }
}
