using foodmarket.Infrastructure.Integrations.MoySklad;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace foodmarket.Api.Controllers.Admin;

[ApiController]
[Authorize(Policy = "AdminAccess")]
[Route("api/admin/jobs")]
public class AdminJobsController : ControllerBase
{
    private readonly ImportJobRegistry _jobs;
    public AdminJobsController(ImportJobRegistry jobs) => _jobs = jobs;

    public record JobView(
        Guid Id,
        string Kind,
        string Status,
        string? Stage,
        DateTime StartedAt,
        DateTime? FinishedAt,
        int Total, int Created, int Updated, int Skipped, int Deleted, int GroupsCreated,
        string? Message,
        IReadOnlyList<string> Errors);

    private static JobView Project(ImportJobProgress j) => new(
        j.Id, j.Kind, j.Status.ToString(), j.Stage, j.StartedAt, j.FinishedAt,
        j.Total, j.Created, j.Updated, j.Skipped, j.Deleted, j.GroupsCreated,
        j.Message, j.Errors.TakeLast(20).ToList());

    [HttpGet("{id:guid}")]
    public ActionResult<JobView> Get(Guid id)
    {
        var j = _jobs.Get(id);
        return j is null ? NotFound() : Project(j);
    }

    [HttpGet("recent")]
    public IReadOnlyList<JobView> Recent([FromQuery] int take = 10)
        => _jobs.RecentlyFinished(take).Select(Project).ToList();
}
