using JobsMedical.Web.Data;
using JobsMedical.Web.Models;
using JobsMedical.Web.Services.Scraping;
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 IndexModel : PageModel
{
    private readonly AppDbContext _db;
    private readonly IngestionService _ingest;

    public IndexModel(AppDbContext db, IngestionService ingest)
    {
        _db = db;
        _ingest = ingest;
    }

    public List<RawListing> Queue { get; private set; } = new();
    public List<RawListing> Flagged { get; private set; } = new();
    public IReadOnlyList<string> SourceNames { get; private set; } = new List<string>();
    public int PublishedShifts { get; private set; }
    public int PublishedJobs { get; private set; }

    [BindProperty] public string? SourceChannel { get; set; }
    [BindProperty] public string? RawText { get; set; }

    [TempData] public string? IngestMessage { get; set; }

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

    public async Task<IActionResult> OnPostAddAsync()
    {
        if (!string.IsNullOrWhiteSpace(RawText))
        {
            _db.RawListings.Add(new RawListing
            {
                SourceChannel = string.IsNullOrWhiteSpace(SourceChannel) ? "ورود دستی" : SourceChannel.Trim(),
                RawText = RawText.Trim(),
                Status = RawListingStatus.New,
            });
            await _db.SaveChangesAsync();
        }
        return RedirectToPage();
    }

    public async Task<IActionResult> OnPostRunIngestionAsync()
    {
        var s = await _ingest.RunAsync();
        IngestMessage = $"جمع‌آوری انجام شد — {s.TotalQueued} در صف، {s.TotalFlagged} پرچم‌خورده، " +
                        $"{s.TotalSpam} اسپم، {s.TotalDuplicates} تکراری.";
        return RedirectToPage();
    }

    private async Task LoadAsync()
    {
        Queue = await _db.RawListings
            .Where(r => r.Status == RawListingStatus.New)
            .OrderByDescending(r => r.Confidence).ThenByDescending(r => r.FetchedAt).ToListAsync();
        Flagged = await _db.RawListings
            .Where(r => r.Status == RawListingStatus.Flagged)
            .OrderByDescending(r => r.FetchedAt).ToListAsync();
        SourceNames = _ingest.SourceNames;
        PublishedShifts = await _db.Shifts.CountAsync(s => s.Source != ShiftSource.Direct);
        PublishedJobs = await _db.JobOpenings.CountAsync();
    }
}
