using JobsMedical.Web.Data;
using JobsMedical.Web.Models;
using JobsMedical.Web.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace JobsMedical.Web.Pages.Calendar;

public class IndexModel : PageModel
{
    private readonly AppDbContext _db;
    public IndexModel(AppDbContext db) => _db = db;

    [BindProperty(SupportsGet = true)] public int? FacilityId { get; set; }
    [BindProperty(SupportsGet = true)] public int WeekOffset { get; set; } // 0 = current week

    public List<Facility> Facilities { get; private set; } = new();
    public DateOnly WeekStart { get; private set; }
    public DateOnly Today { get; private set; }

    /// <summary>7 days (Saturday→Friday), each with its open shifts.</summary>
    public List<(DateOnly Date, List<Shift> Shifts)> Days { get; private set; } = new();

    public async Task OnGetAsync()
    {
        Today = DateOnly.FromDateTime(DateTime.UtcNow);
        Facilities = await _db.Facilities.OrderBy(f => f.Name).ToListAsync();

        WeekStart = JalaliDate.StartOfPersianWeek(Today).AddDays(WeekOffset * 7);
        var weekEnd = WeekStart.AddDays(6);

        var q = _db.Shifts
            .Include(s => s.Facility)
            .Where(s => s.Status == ShiftStatus.Open && s.Date >= WeekStart && s.Date <= weekEnd);

        if (FacilityId is not null) q = q.Where(s => s.FacilityId == FacilityId);

        var shifts = await q.OrderBy(s => s.StartTime).ToListAsync();

        Days = Enumerable.Range(0, 7)
            .Select(i => WeekStart.AddDays(i))
            .Select(d => (d, shifts.Where(s => s.Date == d).ToList()))
            .ToList();
    }
}
