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

namespace JobsMedical.Web.Pages.Me;

/// <summary>«پسندیده‌ها» — the listings the logged-in user has liked (jobs, shifts, talent), newest
/// first. Only still-open listings are shown; un-liking is done with the same heart button.</summary>
[Authorize]
public class LikedModel : PageModel
{
    private readonly AppDbContext _db;
    public LikedModel(AppDbContext db) => _db = db;

    public List<JobOpening> Jobs { get; private set; } = new();
    public List<Shift> Shifts { get; private set; } = new();
    public List<TalentListing> Talent { get; private set; } = new();
    public int Total => Jobs.Count + Shifts.Count + Talent.Count;

    public async Task OnGetAsync()
    {
        var uid = int.Parse(User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)!.Value);
        var likes = await _db.Likes.Where(l => l.UserId == uid)
            .OrderByDescending(l => l.CreatedAt).ToListAsync();

        var jobIds = likes.Where(l => l.TargetType == LikeTargetType.Job).Select(l => l.TargetId).ToList();
        var shiftIds = likes.Where(l => l.TargetType == LikeTargetType.Shift).Select(l => l.TargetId).ToList();
        var talentIds = likes.Where(l => l.TargetType == LikeTargetType.Talent).Select(l => l.TargetId).ToList();

        Jobs = await _db.JobOpenings
            .Include(j => j.Facility).ThenInclude(f => f.City)
            .Include(j => j.Facility).ThenInclude(f => f.District)
            .Include(j => j.Role)
            .Where(j => jobIds.Contains(j.Id) && j.Status == ShiftStatus.Open).ToListAsync();
        Shifts = await _db.Shifts
            .Include(s => s.Facility).ThenInclude(f => f.City)
            .Include(s => s.Role)
            .Where(s => shiftIds.Contains(s.Id) && s.Status == ShiftStatus.Open).ToListAsync();
        Talent = await _db.TalentListings
            .Include(t => t.City).Include(t => t.District).Include(t => t.Role)
            .Where(t => talentIds.Contains(t.Id) && t.Status == ShiftStatus.Open).ToListAsync();
    }
}
