using ExpenseTracker.Api.Data; using ExpenseTracker.Api.DTOs; using ExpenseTracker.Api.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace ExpenseTracker.Api.Controllers; /// Endpoints for managing budget months. [ApiController] [Route("api/months")] [Produces("application/json")] public class MonthsController : ControllerBase { private readonly AppDbContext _db; private readonly ILogger _logger; public MonthsController(AppDbContext db, ILogger logger) { _db = db; _logger = logger; } // ── GET /api/months ─────────────────────────────────────────────────────── /// Returns all months sorted by year then month number, descending. [HttpGet] [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] public async Task GetAll() { var months = await _db.Months .OrderByDescending(m => m.Year) .ThenByDescending(m => m.MonthNumber) .Select(m => new MonthDto(m.Id, m.Year, m.MonthNumber, m.DefaultSalary, m.CreatedAt)) .ToListAsync(); return Ok(months); } // ── POST /api/months ────────────────────────────────────────────────────── /// Creates a new month. Automatically inserts an INCOME entry for the salary if > 0. [HttpPost] [ProducesResponseType(typeof(MonthDto), StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status409Conflict)] public async Task Create([FromBody] CreateMonthDto dto) { // FluentValidation auto-validation handles 400 before we get here. bool exists = await _db.Months .AnyAsync(m => m.Year == dto.Year && m.MonthNumber == dto.Month); if (exists) { _logger.LogWarning("Conflict: month {Year}-{Month} already exists.", dto.Year, dto.Month); return Conflict(new { error = "A month with this year and month number already exists." }); } var month = new Month { Id = Guid.NewGuid(), Year = dto.Year, MonthNumber = dto.Month, DefaultSalary = dto.DefaultSalary, CreatedAt = DateTime.UtcNow }; _db.Months.Add(month); if (dto.DefaultSalary > 0) { var income = new Entry { Id = Guid.NewGuid(), MonthId = month.Id, Type = EntryType.INCOME, Amount = dto.DefaultSalary, Label = "Salaire", CategoryId = null, EntryDate = new DateOnly(dto.Year, dto.Month, 1), CreatedAt = DateTime.UtcNow }; _db.Entries.Add(income); } await _db.SaveChangesAsync(); _logger.LogInformation("Month {Year}-{Month} created with id {Id}.", month.Year, month.MonthNumber, month.Id); var result = new MonthDto(month.Id, month.Year, month.MonthNumber, month.DefaultSalary, month.CreatedAt); return CreatedAtAction(nameof(GetSummary), new { id = month.Id }, result); } // ── GET /api/months/{id}/summary ────────────────────────────────────────── /// Returns the balance summary for a given month. [HttpGet("{id:guid}/summary")] [ProducesResponseType(typeof(MonthSummaryDto), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task GetSummary(Guid id) { var month = await _db.Months.FindAsync(id); if (month is null) { _logger.LogWarning("GetSummary: month {Id} not found.", id); return NotFound(new { error = "Month not found." }); } var entries = await _db.Entries .Where(e => e.MonthId == id) .ToListAsync(); decimal totalIncome = entries.Where(e => e.Type == EntryType.INCOME).Sum(e => e.Amount); decimal totalExpense = entries.Where(e => e.Type == EntryType.EXPENSE).Sum(e => e.Amount); decimal balance = totalIncome - totalExpense; var summary = new MonthSummaryDto( MonthId: month.Id, Year: month.Year, MonthNumber: month.MonthNumber, TotalIncome: totalIncome, TotalExpense: totalExpense, Balance: balance); return Ok(summary); } }