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

    public List<Facility> MyFacilities { get; private set; } = new();
    public List<Role> Roles { get; private set; } = new();
    public string? Error { get; private set; }

    [BindProperty] public int FacilityId { get; set; }
    [BindProperty] public int RoleId { get; set; }
    [BindProperty] public string Title { get; set; } = "";
    [BindProperty] public EmploymentType EmploymentType { get; set; }
    [BindProperty] public long? SalaryMin { get; set; }
    [BindProperty] public long? SalaryMax { get; set; }
    [BindProperty] public bool Negotiable { get; set; }
    [BindProperty] public string? Description { get; set; }
    [BindProperty] public string? Requirements { get; set; }

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

    public async Task<IActionResult> OnPostAsync()
    {
        await LoadListsAsync();
        if (!MyFacilities.Any(f => f.Id == FacilityId))
        {
            Error = "این مرکز متعلق به شما نیست.";
            return Page();
        }
        if (string.IsNullOrWhiteSpace(Title)) { Error = "عنوان موقعیت الزامی است."; return Page(); }

        _db.JobOpenings.Add(new JobOpening
        {
            FacilityId = FacilityId,
            RoleId = RoleId,
            Title = Title.Trim(),
            EmploymentType = EmploymentType,
            SalaryMin = Negotiable ? null : SalaryMin,
            SalaryMax = Negotiable ? null : SalaryMax,
            Description = Description,
            Requirements = Requirements,
            Status = ShiftStatus.Open,
            Source = ShiftSource.Direct,
        });
        await _db.SaveChangesAsync();
        return RedirectToPage("/Employer/Index");
    }

    private async Task LoadListsAsync()
    {
        var userId = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
        MyFacilities = await _db.Facilities.Include(f => f.City)
            .Where(f => f.OwnerUserId == userId).OrderBy(f => f.Name).ToListAsync();
        Roles = await _db.Roles.Where(r => r.IsActive).OrderBy(r => r.SortOrder).ToListAsync();
    }
}
