
using administration.Models;
using administration.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace administration.Controllers
{
    /// <summary>
    /// Contrôleur API pour la gestion des dépenses de l'utilisateur.
    /// Fournit des points de terminaison pour récupérer les dépenses du mois en cours
    /// pour l'utilisateur actuellement connecté.
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class ExpenseController : Controller
    {
        private readonly FinancesContext _context;
        private readonly IUserSessionService _userSession;

        /// <summary>
        /// Initialise une nouvelle instance du contrôleur <see cref="ExpenseController"/>.
        /// </summary>
        /// <param name="context">Contexte de base de données des finances.</param>
        /// <param name="userSession">Service de session utilisateur pour obtenir l'utilisateur courant.</param>
        public ExpenseController(FinancesContext context, IUserSessionService userSession)
        {
            _context = context;
            _userSession = userSession;
        }

        /// <summary>
        /// Récupère la dernière dépense du mois en cours pour l'utilisateur connecté.
        /// </summary>
        /// <returns>
        /// Un objet <see cref="IActionResult"/> contenant la dépense trouvée ou un code d'erreur approprié.
        /// </returns>
        [HttpGet("last_expenses")]
        public IActionResult GetRightExpenses()
        {
            try
            {
                if (_userSession.UserId == null)
                    return Unauthorized("Utilisateur non connecté.");
                var expense = _context.Expenses
                    .Where(e => e.UserId == _userSession.UserId &&
                                e.Date.Month == DateTime.Now.Month)
                    .OrderByDescending(e => e.Date)
                    .FirstOrDefault();

                if (expense == null)
                    return NotFound("Aucune dépense trouvée pour ce mois.");

                var additionalSources = (
                    from additional in _context.AdditionalSources
                    join logo in _context.Logos on additional.LogoId equals logo.Id
                    where additional.UserId == _userSession.UserId &&
                          additional.Date.Month == DateTime.Now.Month &&
                          (additional.TransactionType == "expense" || additional.TransactionType == "sub")
                    select new
                    {
                        additional.Id,
                        additional.TransactionType,
                        additional.Amount,
                        additional.Description,
                        additional.Date,
                        Logo = new
                        {
                            logo.Id,
                            logo.Name,
                            logo.Image
                        }
                    }
                ).ToList();

                var totalExpenses = expense.Rent
                    + expense.Electricity
                    + expense.Trash
                    + expense.Wifi
                    + expense.Groceries
                    + expense.Insurance
                    + expense.Saving;

                var totalAdditionalExpense = additionalSources
                    .Where(a => a.TransactionType == "expense")
                    .Sum(a => a.Amount);

                var totalAdditionalSub = additionalSources
                    .Where(a => a.TransactionType == "sub")
                    .Sum(a => a.Amount);

                var result = new
                {
                    expense.Id,
                    expense.Rent,
                    expense.Electricity,
                    expense.Trash,
                    expense.Wifi,
                    expense.Groceries,
                    expense.Insurance,
                    expense.Date,
                    expense.Saving,
                    AdditionalSourcesExpense = additionalSources.Where(a => a.TransactionType == "expense").ToList(),
                    AdditionalSourcesSub = additionalSources.Where(a => a.TransactionType == "sub").ToList(),
                    Total = totalExpenses + totalAdditionalExpense + totalAdditionalSub
                };

                return Ok(result);
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Erreur serveur : {ex.Message}, Méthode GetAdditionalRevenues");
            }
        }
    }
}

