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

public class IndexModel : PageModel
{
    private readonly AppDbContext _db;
    private readonly InterestService _interest;

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

    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; }

    public bool Saved { get; private set; }

    public async Task OnGetAsync()
    {
        await LoadListsAsync();
        var prefs = await _interest.GetPreferencesAsync();
        if (prefs is not null)
        {
            RoleId = prefs.RoleId;
            CityId = prefs.CityId;
            PreferredShiftType = prefs.PreferredShiftType;
            MinPay = prefs.MinPay;
            Gender = prefs.Gender;
        }
    }

    public async Task<IActionResult> OnPostAsync()
    {
        await _interest.SavePreferencesAsync(RoleId, CityId, PreferredShiftType, MinPay, Gender);
        // Back to home so the personalized feed is the immediate payoff.
        TempData["prefsSaved"] = true;
        return RedirectToPage("/Index");
    }

    private async Task LoadListsAsync()
    {
        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();
    }
}
