using JobTrackerApi.Models;
using JobTrackerApi.Services;
using JobTrackerApi.Tests.TestSupport;
using Microsoft.EntityFrameworkCore;
using Xunit;

namespace JobTrackerApi.Tests;

public sealed class JobOpportunitySyncTests
{
    [Fact]
    public async Task Backfill_links_each_legacy_application_once()
    {
        await using var db = TestHostFactory.CreateInMemoryDb();
        var company = new Company { OwnerUserId = "user-1", Name = "Acme" };
        db.Companies.Add(company);
        await db.SaveChangesAsync();
        db.JobApplications.Add(new JobApplication
        {
            OwnerUserId = "user-1",
            CompanyId = company.Id,
            JobTitle = "Platform Engineer",
            Location = "Oslo",
            SavedAt = new DateTime(2026, 7, 1, 10, 0, 0, DateTimeKind.Utc),
        });
        await db.SaveChangesAsync();

        Assert.Equal(1, await JobOpportunitySync.BackfillLegacyAsync(db));
        Assert.Equal(0, await JobOpportunitySync.BackfillLegacyAsync(db));

        var application = await db.JobApplications.IgnoreQueryFilters().Include(item => item.Job).SingleAsync();
        Assert.NotNull(application.JobId);
        Assert.Equal("Platform Engineer", application.Job!.JobTitle);
        Assert.Equal("Oslo", application.Job.Location);
        Assert.Equal("legacy", application.Job.Source);
        Assert.Equal(1, await db.Jobs.IgnoreQueryFilters().CountAsync());
    }
}
