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

    public List<Report> Reports { get; private set; } = new();

    public async Task OnGetAsync() =>
        Reports = await _db.Reports
            .OrderBy(r => r.Status).ThenByDescending(r => r.CreatedAt)
            .Take(200).ToListAsync();

    public async Task<IActionResult> OnPostResolveAsync(int id) => await SetStatus(id, ReportStatus.Resolved);
    public async Task<IActionResult> OnPostDismissAsync(int id) => await SetStatus(id, ReportStatus.Dismissed);

    private async Task<IActionResult> SetStatus(int id, ReportStatus st)
    {
        var r = await _db.Reports.FindAsync(id);
        if (r is null) return NotFound();
        r.Status = st;
        await _db.SaveChangesAsync();
        return RedirectToPage();
    }

    public static string TargetUrl(Report r) => r.TargetType switch
    {
        ReportTargetType.Shift => $"/Shifts/Details/{r.TargetId}",
        ReportTargetType.Job => $"/Jobs/Details/{r.TargetId}",
        ReportTargetType.Facility => "/Admin/Facilities",
        _ => "/Admin/Users",
    };
}
