using JobTrackerApi.Data;
using JobTrackerApi.Models;
using Microsoft.EntityFrameworkCore;

namespace JobTrackerApi.Services;

public static class JobOpportunitySync
{
    public static Job Create(JobApplication application, string? source = null, string? countryCode = null)
    {
        var opportunity = new Job { Source = source, CountryCode = countryCode };
        Apply(application, opportunity);
        return opportunity;
    }

    public static void Apply(JobApplication application, Job opportunity)
    {
        opportunity.OwnerUserId = application.OwnerUserId;
        opportunity.CompanyId = application.CompanyId;
        opportunity.JobTitle = application.JobTitle;
        opportunity.Location = application.Location;
        opportunity.JobUrl = application.JobUrl;
        opportunity.Description = application.Description;
        opportunity.TranslatedDescription = application.TranslatedDescription;
        opportunity.DescriptionLanguage = application.DescriptionLanguage;
        opportunity.ShortSummary = application.ShortSummary;
        opportunity.Tags = application.Tags;
        opportunity.Deadline = application.Deadline;
        opportunity.Salary = application.Salary;
        opportunity.SalaryMin = application.SalaryMin;
        opportunity.SalaryMax = application.SalaryMax;
        opportunity.SalaryCurrency = application.SalaryCurrency;
        opportunity.SalaryPeriod = application.SalaryPeriod;
        opportunity.SavedAt = application.SavedAt;
    }

    public static async Task<int> BackfillLegacyAsync(JobTrackerContext db, CancellationToken cancellationToken = default)
    {
        var applications = await db.JobApplications
            .IgnoreQueryFilters()
            .Where(application => application.JobId == null)
            .ToListAsync(cancellationToken);

        foreach (var application in applications)
            application.Job = Create(application, "legacy");

        if (applications.Count > 0)
            await db.SaveChangesAsync(cancellationToken);

        return applications.Count;
    }
}
