using System.Security.Claims;
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.Employer;

[Authorize]
public class VerifyModel : PageModel
{
    private readonly AppDbContext _db;
    public VerifyModel(AppDbContext db) => _db = db;

    public Facility Facility { get; private set; } = null!;
    public List<FacilityDocument> Docs { get; private set; } = new();
    [TempData] public string? Msg { get; set; }

    private static readonly string[] Allowed = { "image/jpeg", "image/png", "image/webp", "application/pdf" };
    private const long MaxBytes = 5 * 1024 * 1024;   // 5 MB per file

    private int Uid => int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);

    public async Task<IActionResult> OnGetAsync(int id)
    {
        var f = await _db.Facilities.Include(x => x.City).Include(x => x.District)
            .FirstOrDefaultAsync(x => x.Id == id && x.OwnerUserId == Uid);
        if (f is null) return NotFound();
        Facility = f;
        Docs = await _db.FacilityDocuments.Where(d => d.FacilityId == id)
            .OrderByDescending(d => d.UploadedAt).ToListAsync();
        return Page();
    }

    public async Task<IActionResult> OnPostUploadAsync(int id, List<IFormFile> files)
    {
        var f = await _db.Facilities.FirstOrDefaultAsync(x => x.Id == id && x.OwnerUserId == Uid);
        if (f is null) return NotFound();

        int added = 0;
        foreach (var file in files ?? new())
        {
            if (file.Length == 0) continue;
            if (file.Length > MaxBytes) { Msg = "هر فایل باید کمتر از ۵ مگابایت باشد."; continue; }
            var ct = (file.ContentType ?? "").ToLowerInvariant();
            if (!Allowed.Contains(ct)) { Msg = "فقط تصویر (JPG/PNG/WebP) یا PDF مجاز است."; continue; }

            using var ms = new MemoryStream();
            await file.CopyToAsync(ms);
            _db.FacilityDocuments.Add(new FacilityDocument
            {
                FacilityId = id,
                FileName = Path.GetFileName(file.FileName),
                ContentType = ct,
                Size = file.Length,
                Data = ms.ToArray(),
            });
            added++;
        }

        if (added > 0)
        {
            if (f.Verification != VerificationStatus.Verified)
            {
                f.Verification = VerificationStatus.Pending;     // submitting docs = request review
                f.VerificationRequestedAt = DateTime.UtcNow;
                f.VerificationNote = null;
            }
            await _db.SaveChangesAsync();
            Msg = $"{added} سند بارگذاری و برای بررسی ارسال شد.";
        }
        return RedirectToPage(new { id });
    }

    public async Task<IActionResult> OnPostDeleteDocAsync(int id, int docId)
    {
        var f = await _db.Facilities.FirstOrDefaultAsync(x => x.Id == id && x.OwnerUserId == Uid);
        if (f is null) return NotFound();
        var d = await _db.FacilityDocuments.FirstOrDefaultAsync(x => x.Id == docId && x.FacilityId == id);
        if (d is not null) { _db.FacilityDocuments.Remove(d); await _db.SaveChangesAsync(); }
        return RedirectToPage(new { id });
    }
}
