using System.Threading.Tasks;
using API.Data;
using API.DTOs;
using API.DTOs.Progress;
using API.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace API.Controllers;
#nullable enable
/// 
/// For the Panels app explicitly
/// 
[AllowAnonymous]
public class PanelsController : BaseApiController
{
    private readonly IReaderService _readerService;
    private readonly IUnitOfWork _unitOfWork;
    public PanelsController(IReaderService readerService, IUnitOfWork unitOfWork)
    {
        _readerService = readerService;
        _unitOfWork = unitOfWork;
    }
    /// 
    /// Saves the progress of a given chapter.
    /// 
    /// 
    /// 
    /// 
    [HttpPost("save-progress")]
    public async Task SaveProgress(ProgressDto dto, [FromQuery] string apiKey)
    {
        if (string.IsNullOrEmpty(apiKey)) return Unauthorized("ApiKey is required");
        var userId = await _unitOfWork.UserRepository.GetUserIdByApiKeyAsync(apiKey);
        await _readerService.SaveReadingProgress(dto, userId);
        return Ok();
    }
    /// 
    /// Gets the Progress of a given chapter
    /// 
    /// 
    /// 
    /// The number of pages read, 0 if none read
    [HttpGet("get-progress")]
    public async Task> GetProgress(int chapterId, [FromQuery] string apiKey)
    {
        if (string.IsNullOrEmpty(apiKey)) return Unauthorized("ApiKey is required");
        var userId = await _unitOfWork.UserRepository.GetUserIdByApiKeyAsync(apiKey);
        var progress = await _unitOfWork.AppUserProgressRepository.GetUserProgressDtoAsync(chapterId, userId);
        if (progress == null) return Ok(new ProgressDto()
        {
            PageNum = 0,
            ChapterId = chapterId,
            VolumeId = 0,
            SeriesId = 0,
        });
        return Ok(progress);
    }
}