using Microsoft.Extensions.Options;

namespace NeonSprawl.Server.Game.PositionState;

/// <summary>Runs DDL and dev-player seed once when the host starts (PostgreSQL path only).</summary>
internal sealed class PostgresDevPlayerSeedHostedService(
    Npgsql.NpgsqlDataSource dataSource,
    IOptions<GamePositionOptions> positionOptions) : IHostedService
{
    private readonly GamePositionOptions gameOptions = RequireDevPlayer(positionOptions.Value);

    private static GamePositionOptions RequireDevPlayer(GamePositionOptions options)
    {
        if (string.IsNullOrWhiteSpace(options.DevPlayerId))
        {
            throw new InvalidOperationException("Game:DevPlayerId must be non-empty.");
        }

        return options;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        PostgresPositionBootstrap.EnsureSchema(dataSource);
        PostgresPositionBootstrap.SeedDevPlayer(dataSource, gameOptions);
        return Task.CompletedTask;
    }

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