using System.Security.Claims;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using JobTrackerApi.Tests.TestSupport;
using Microsoft.EntityFrameworkCore;
using Xunit;

namespace JobTrackerApi.Tests;

public sealed class LocalAuthIdentityTests
{
    [Fact]
    public void GetRequiredUserId_returns_null_when_subject_claim_is_missing()
    {
        var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
        {
            new Claim(ClaimTypes.Email, "ghost@example.com")
        }, "local"));

        var userId = LocalAuthIdentity.GetRequiredUserId(principal);

        Assert.Null(userId);
    }

    [Fact]
    public void GetRequiredUserId_returns_nameidentifier_when_present()
    {
        var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
        {
            new Claim(ClaimTypes.NameIdentifier, "user-123")
        }, "local"));

        var userId = LocalAuthIdentity.GetRequiredUserId(principal);

        Assert.Equal("user-123", userId);
    }

    [Fact]
    public async Task Owner_scoped_query_filters_fail_closed_when_current_user_is_missing()
    {
        await using var db = TestHostFactory.CreateInMemoryDb(null);
        db.Companies.Add(new Company { Name = "Secret Co", OwnerUserId = "user-1" });
        db.JobApplications.Add(new JobApplication { JobTitle = "Secret Job", Status = "Applied", OwnerUserId = "user-1" });
        db.UserRuleSettings.Add(new UserRuleSettings { OwnerUserId = "user-1", AppliedFollowUpDays = 5 });
        await db.SaveChangesAsync();

        Assert.Empty(await db.Companies.ToListAsync());
        Assert.Empty(await db.JobApplications.ToListAsync());
        Assert.Empty(await db.UserRuleSettings.ToListAsync());
    }
}
