using System.Diagnostics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OneForMe.Data;
using OneForMe.Models;

namespace OneForMe.Controllers;

[Authorize]
public class HomeController : Controller
{
    private readonly ApplicationDbContext _context;

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

    public IActionResult Index()
    {
        if (User.Identity?.IsAuthenticated == true)
        {
            return RedirectToAction("Dashboard");
        }
        return RedirectToAction("Login", "AccountController");
    }

    public async Task<IActionResult> Dashboard()
    {
        var userEmail = User.Identity?.Name;
        
        var createdOrders = await _context.Orders
            .Where(o => o.CreatorName == userEmail)
            .Include(o => o.MenuItems)
            .Include(o => o.OrderItems)
            .ThenInclude(oi => oi.MenuItem)
            .ToListAsync();

        var joinedOrders = await _context.Orders
            .Where(o => o.OrderItems.Any(oi => oi.ParticipantEmail == userEmail || oi.ParticipantName == userEmail))
            .Include(o => o.MenuItems)
            .Include(o => o.OrderItems)
            .ThenInclude(oi => oi.MenuItem)
            .ToListAsync();

        var viewModel = new DashboardViewModel
        {
            CreatedOrders = createdOrders,
            JoinedOrders = joinedOrders
        };

        return View(viewModel);
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
