using Microsoft.AspNetCore.Mvc;
using SQLiteEF;
using static Microsoft.AspNetCore.Http.StatusCodes;

namespace API.Controllers;

[ApiController]
[Route("[controller]")]
public class TimeTrackController(Context databaseContext) : ApiController(typeof(TimeTrackController))
{
    
    [HttpGet("{steamId}")]
    [ProducesResponseType<Dictionary<ulong, TrackedTime[]>>(Status200OK)]
    [ProducesResponseType(Status404NotFound)]
    public IActionResult GetTrackedTime(ulong steamId)
    {
        if (databaseContext.Players.Find(steamId) is not { } player)
            return NotFound();
        databaseContext.Entry(player).Collection(p => p.TrackedTimes).Load();
        Dictionary<ulong, TrackedTime[]> ret = player.TrackedTimes
            .GroupBy(t => t.Game)
            .ToDictionary(t => t.Key.AppId, t => t.ToArray());
        return Ok(ret);
    }
    
    [HttpGet("{steamId}/{appId}")]
    [ProducesResponseType<TrackedTime[]>(Status200OK)]
    [ProducesResponseType(Status404NotFound)]
    public IActionResult GetTrackedTimeForApp(ulong steamId, ulong appId)
    {
        if (databaseContext.Players.Find(steamId) is not { } player)
            return NotFound();
        if (databaseContext.Games.Find(appId) is not { } game)
            return NotFound();
        databaseContext.Entry(player).Collection(p => p.TrackedTimes).Load();
        return Ok(player.TrackedTimes.Where(t => t.Game == game).ToArray());
    }
    
    [HttpGet("{steamId}/Total")]
    [ProducesResponseType<ulong>(Status200OK)]
    [ProducesResponseType(Status404NotFound)]
    public IActionResult GetTrackedTimeTotal(ulong steamId)
    {
        if (databaseContext.Players.Find(steamId) is not { } player)
            return NotFound();
        databaseContext.Entry(player).Collection(p => p.TrackedTimes).Load();
        ulong[] times = player.TrackedTimes.GroupBy(t => t.Game)
            .Select(t => t.MaxBy(time => time.TimePlayed)?.TimePlayed ?? 0)
            .ToArray();
        ulong sum = 0;
        foreach (ulong time in times)
            sum += time;
        return Ok(sum);
    }
    
    [HttpGet("{steamId}/Total/PerGame")]
    [ProducesResponseType<Dictionary<ulong, ulong>>(Status200OK)]
    [ProducesResponseType(Status404NotFound)]
    public IActionResult GetTrackedTimeAll(ulong steamId)
    {
        if (databaseContext.Players.Find(steamId) is not { } player)
            return NotFound();
        databaseContext.Entry(player).Collection(p => p.TrackedTimes).Load();
        Dictionary<ulong, ulong> trackedTimes = player.TrackedTimes
            .GroupBy(t => t.Game)
            .ToDictionary(t => t.Key.AppId, t => t.MaxBy(time => time.TimePlayed)?.TimePlayed??0);
        
        return Ok(trackedTimes);
    }
}