using Microsoft.EntityFrameworkCore;

public class PatientPhiMigrationService : IHostedService
{
    private readonly IServiceProvider _services;
    private readonly ILogger<PatientPhiMigrationService> _logger;

    public PatientPhiMigrationService(
        IServiceProvider services,
        ILogger<PatientPhiMigrationService> logger)
    {
        _services = services;
        _logger = logger;
    }

    public async Task StartAsync(CancellationToken ct)
    {
        using var scope = _services.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        var crypto = scope.ServiceProvider.GetRequiredService<IPhiEncryptionService>();

        var patients = await db.Patients.ToListAsync(ct);
        var migrated = 0;

        foreach (var patient in patients)
        {
            if (patient.NameSearchToken is not null && crypto.IsEncrypted(patient.FirstName))
                continue;

            patient.NameSearchToken = crypto.ComputeNameSearchToken(
                patient.FirstName, patient.LastName);
            migrated++;
        }

        if (migrated > 0)
        {
            await db.SaveChangesAsync(ct);
            _logger.LogInformation(
                "PHI migration: updated {Count} patient search tokens", migrated);
        }
    }

    public Task StopAsync(CancellationToken ct) => Task.CompletedTask;
}