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> Awaiting { get; private set; } = new();   // requested review (Pending)
    public List<Facility> Others { get; private set; } = new();      // unverified / rejected, no pending request
    public List<Facility> Verified { get; private set; } = new();
    [TempData] public string? Msg { get; set; }

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

    public async Task<IActionResult> OnPostVerifyAsync(int id)
    {
        var f = await _db.Facilities.FindAsync(id);
        if (f is null) return NotFound();
        f.IsVerified = true;
        f.Verification = VerificationStatus.Verified;
        f.VerificationNote = null;
        await _db.SaveChangesAsync();
        Msg = $"«{f.Name}» تأیید شد.";
        return RedirectToPage();
    }

    public async Task<IActionResult> OnPostRejectAsync(int id, string? note)
    {
        var f = await _db.Facilities.FindAsync(id);
        if (f is null) return NotFound();
        f.IsVerified = false;
        f.Verification = VerificationStatus.Rejected;
        f.VerificationNote = string.IsNullOrWhiteSpace(note) ? "مدارک کافی نبود." : note.Trim();
        await _db.SaveChangesAsync();
        Msg = $"«{f.Name}» رد شد.";
        return RedirectToPage();
    }

    public async Task<IActionResult> OnPostUnverifyAsync(int id)
    {
        var f = await _db.Facilities.FindAsync(id);
        if (f is null) return NotFound();
        f.IsVerified = false;
        f.Verification = VerificationStatus.Unverified;
        await _db.SaveChangesAsync();
        Msg = $"تأیید «{f.Name}» لغو شد.";
        return RedirectToPage();
    }

    private async Task LoadAsync()
    {
        var all = await _db.Facilities
            .Include(f => f.City).Include(f => f.District).Include(f => f.OwnerUser)
            .Include(f => f.Documents)
            .OrderByDescending(f => f.VerificationRequestedAt).ThenBy(f => f.Name).ToListAsync();
        Awaiting = all.Where(f => f.Verification == VerificationStatus.Pending).ToList();
        Verified = all.Where(f => f.IsVerified).ToList();
        Others = all.Where(f => !f.IsVerified && f.Verification != VerificationStatus.Pending).ToList();
    }
}
