using System.Security.Claims;
using JobsMedical.Web.Data;
using JobsMedical.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace JobsMedical.Web.Pages.Employer;

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

    public record FacilityCard(Facility Facility, int OpenShifts, int OpenJobs, int Applicants);
    public List<FacilityCard> Facilities { get; private set; } = new();

    public async Task OnGetAsync()
    {
        var userId = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
        var today = DateOnly.FromDateTime(DateTime.UtcNow);

        var facilities = await _db.Facilities
            .Include(f => f.City).Include(f => f.District)
            .Where(f => f.OwnerUserId == userId)
            .OrderBy(f => f.Name).ToListAsync();

        foreach (var f in facilities)
        {
            var openShifts = await _db.Shifts.CountAsync(s =>
                s.FacilityId == f.Id && s.Status == ShiftStatus.Open && s.Date >= today);
            var openJobs = await _db.JobOpenings.CountAsync(j =>
                j.FacilityId == f.Id && j.Status == ShiftStatus.Open);

            var shiftIds = await _db.Shifts.Where(s => s.FacilityId == f.Id).Select(s => s.Id).ToListAsync();
            var jobIds = await _db.JobOpenings.Where(j => j.FacilityId == f.Id).Select(j => j.Id).ToListAsync();
            var applicants = await _db.InterestEvents.CountAsync(e =>
                e.EventType == InterestEventType.Apply &&
                ((e.ShiftId != null && shiftIds.Contains(e.ShiftId.Value)) ||
                 (e.JobOpeningId != null && jobIds.Contains(e.JobOpeningId.Value))));

            Facilities.Add(new FacilityCard(f, openShifts, openJobs, applicants));
        }
    }
}
