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.Recommendations;

/// <summary>
/// Dedicated «پیشنهادهای ویژه شما» page: the personalized recommendation feed plus the preference
/// controls that drive it (role/city/shift-type/pay/gender), in one place — moved off the homepage
/// and consolidating the old /Preferences screen so the settings live next to their result.
/// </summary>
public class IndexModel : PageModel
{
    private readonly AppDbContext _db;
    private readonly RecommendationService _recs;
    private readonly InterestService _interest;

    public IndexModel(AppDbContext db, RecommendationService recs, InterestService interest)
    {
        _db = db;
        _recs = recs;
        _interest = interest;
    }

    public List<Recommendation> Recommendations { get; private set; } = new();
    public bool HasPersonalization { get; private set; }
    public List<Role> Roles { get; private set; } = new();
    public List<City> Cities { get; private set; } = new();

    [BindProperty] public int? RoleId { get; set; }
    [BindProperty] public int? CityId { get; set; }
    [BindProperty] public ShiftType? PreferredShiftType { get; set; }
    [BindProperty] public long? MinPay { get; set; }
    [BindProperty] public Gender Gender { get; set; }
    [TempData] public bool Saved { get; set; }

    public async Task OnGetAsync() => await LoadAsync();

    public async Task<IActionResult> OnPostAsync()
    {
        await _interest.SavePreferencesAsync(RoleId, CityId, PreferredShiftType, MinPay, Gender);
        Saved = true;
        return RedirectToPage();   // reload so the feed reflects the new preferences immediately
    }

    private async Task LoadAsync()
    {
        Roles = await _db.Roles.Where(r => r.IsActive).OrderBy(r => r.SortOrder).ToListAsync();
        Cities = await _db.Cities.Where(c => c.IsActive).OrderBy(c => c.Name).ToListAsync();
        Recommendations = await _recs.GetForVisitorAsync(12);

        var prefs = await _interest.GetPreferencesAsync();
        HasPersonalization = prefs?.HasAny == true || (await _interest.RecentEventsAsync(1)).Count > 0;
        if (prefs is not null)
        {
            RoleId = prefs.RoleId;
            CityId = prefs.CityId;
            PreferredShiftType = prefs.PreferredShiftType;
            MinPay = prefs.MinPay;
            Gender = prefs.Gender;
        }
    }
}
