using Aberwyn.Data;
using Aberwyn.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;


namespace Aberwyn.Controllers
{
    [Authorize(Roles = "Budget")]
    [ApiController]
    [Route("api/report")]
    public class ReportApiController : ControllerBase


    {

        private readonly ApplicationDbContext _context;

        public ReportApiController(ApplicationDbContext context)
        {
            _context = context;
        }

        [HttpPost]
        public async Task<IActionResult> GetReport([FromBody] BudgetReportRequestDto request)
        {
            var start = new DateTime(request.StartYear, request.StartMonth, 1);
            var end = new DateTime(request.EndYear, request.EndMonth, 1);

            var items = await _context.BudgetItems
                .Include(i => i.BudgetItemDefinition)
                .Include(i => i.BudgetCategory)
                    .ThenInclude(c => c.BudgetPeriod)
                .Where(i =>
                    i.BudgetCategory.BudgetPeriod.Year * 12 + i.BudgetCategory.BudgetPeriod.Month >= start.Year * 12 + start.Month &&
                    i.BudgetCategory.BudgetPeriod.Year * 12 + i.BudgetCategory.BudgetPeriod.Month <= end.Year * 12 + end.Month &&
                    request.DefinitionIds.Contains(i.BudgetItemDefinitionId ?? -1))
                .ToListAsync();

            var grouped = items
                .GroupBy(i => new { i.BudgetCategory.BudgetPeriod.Year, i.BudgetCategory.BudgetPeriod.Month })
                .Select(g => new BudgetReportResultDto
                {
                    Year = g.Key.Year,
                    Month = g.Key.Month,
                    Definitions = g
                        .GroupBy(i => new { i.BudgetItemDefinitionId, i.BudgetItemDefinition.Name })
                        .Select(dg => new DefinitionSumDto
                        {
                            DefinitionId = dg.Key.BudgetItemDefinitionId ?? 0,
                            DefinitionName = dg.Key.Name,
                            TotalAmount = dg.Sum(x => x.Amount)
                        }).ToList()
                })
                .OrderBy(r => r.Year).ThenBy(r => r.Month)
                .ToList();

            return Ok(grouped);
        }


    }
}
