using JobsMedical.Web.Data;
using JobsMedical.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace JobsMedical.Web.Pages.Talent;

public class DetailsModel : PageModel
{
    private readonly AppDbContext _db;
    private readonly JobsMedical.Web.Services.Scraping.SettingsService _settings;

    public DetailsModel(AppDbContext db, JobsMedical.Web.Services.Scraping.SettingsService settings)
    {
        _db = db;
        _settings = settings;
    }

    public TalentListing? Item { get; private set; }
    public string? MapKey { get; private set; }
    public int LikeCount { get; private set; }
    public bool IsLiked { get; private set; }

    public async Task<IActionResult> OnGetAsync(int id)
    {
        Item = await _db.TalentListings
            .Include(t => t.City)
            .Include(t => t.District)
            .Include(t => t.Role)
            .Include(t => t.Contacts)
            .FirstOrDefaultAsync(t => t.Id == id);
        if (Item is null) return NotFound();
        MapKey = (await _settings.GetAsync()).NeshanMapKey;
        LikeCount = await _db.Likes.CountAsync(l => l.TargetType == LikeTargetType.Talent && l.TargetId == id);
        var meId = int.TryParse(User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value, out var n) ? n : (int?)null;
        IsLiked = meId is int u && await _db.Likes.AnyAsync(l => l.UserId == u && l.TargetType == LikeTargetType.Talent && l.TargetId == id);
        return Page();
    }
}
