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

namespace JobsMedical.Web.Pages.Admin;

[Authorize(Roles = "Admin")]
public class FacilitiesModel : PageModel
{
    private readonly AppDbContext _db;
    public FacilitiesModel(AppDbContext db) => _db = db;

    public List<Facility> Pending { get; private set; } = new();
    public List<Facility> Verified { get; private set; } = new();

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

    public async Task<IActionResult> OnPostVerifyAsync(int id) => await SetVerified(id, true);
    public async Task<IActionResult> OnPostUnverifyAsync(int id) => await SetVerified(id, false);

    private async Task<IActionResult> SetVerified(int id, bool value)
    {
        var f = await _db.Facilities.FindAsync(id);
        if (f is null) return NotFound();
        f.IsVerified = value;
        await _db.SaveChangesAsync();
        return RedirectToPage();
    }

    private async Task LoadAsync()
    {
        var all = await _db.Facilities
            .Include(f => f.City).Include(f => f.District).Include(f => f.OwnerUser)
            .OrderBy(f => f.Name).ToListAsync();
        Pending = all.Where(f => !f.IsVerified).ToList();
        Verified = all.Where(f => f.IsVerified).ToList();
    }
}
