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 ReviewsModel : PageModel
{
    private readonly AppDbContext _db;
    public ReviewsModel(AppDbContext db) => _db = db;

    public List<Review> Items { get; private set; } = new();
    [TempData] public string? Msg { get; set; }

    public async Task OnGetAsync()
    {
        Items = await _db.Reviews.Include(r => r.Facility).Include(r => r.User)
            .OrderByDescending(r => r.CreatedAt).Take(200).ToListAsync();
    }

    public async Task<IActionResult> OnPostToggleAsync(int id)
    {
        var r = await _db.Reviews.FindAsync(id);
        if (r is not null) { r.IsApproved = !r.IsApproved; await _db.SaveChangesAsync(); Msg = r.IsApproved ? "نمایش داده شد." : "پنهان شد."; }
        return RedirectToPage();
    }

    public async Task<IActionResult> OnPostDeleteAsync(int id)
    {
        var r = await _db.Reviews.FindAsync(id);
        if (r is not null) { _db.Reviews.Remove(r); await _db.SaveChangesAsync(); Msg = "حذف شد."; }
        return RedirectToPage();
    }
}
