using Microsoft.AspNetCore.Mvc; using Phenix.Models; using Phenix.Services; namespace Phenix.Controllers; public record CreateGameRequest( string Date, string Time, string Home, string Away, int? HomeScore = null, int? AwayScore = null, bool Practice = false, bool Rain = false ); [Route("/api")] public class ApiController : Controller { private readonly IGameService _games; public ApiController(IGameService games) { _games = games; } [HttpGet("results/{year}.json")] public async Task ResultsJson(int year) { var games = await _games.GetAllGames(); var results = games .Where(g => g.Year == year) .Select(g => new Dictionary { ["id"] = g.Id, ["date"] = g.Date, ["time"] = g.Time, ["home"] = g.Home, ["away"] = g.Away, ["year"] = g.Year, [g.Home] = g.HomeScore, [g.Away] = g.AwayScore, ["practice"] = g.Practice, ["rain"] = g.Rain, }); return Json(results); } [HttpGet("available-years.json")] public async Task AvailableYearsJson() { var games = await _games.GetAllGames(); var years = games.Select(g => g.Year).Distinct().OrderByDescending(y => y); return Json(years); } [HttpPost("games")] public async Task CreateGame([FromBody] CreateGameRequest req) { var (game, error) = await _games.CreateNewGame(req.Date, req.Time, req.Home, req.Away); if (game is null) return error switch { "game already exists at this date/time" => Conflict(new { error }), _ => BadRequest(new { error }), }; await _games.UpdateGame(game.Id, req.HomeScore, req.AwayScore, req.Rain, req.Practice); return Created($"/api/games/{game.Id}", game); } [HttpDelete("games")] public async Task ClearGames() { await _games.ClearAllGames(); return NoContent(); } }