using Npgsql;

namespace SpaceGame.Api.Auth.Simulation;

public sealed class AuthSchemaInitializer(NpgsqlDataSource dataSource)
{
    public async Task EnsureSchemaAsync(CancellationToken cancellationToken)
    {
        await using var command = dataSource.CreateCommand("""
            create table if not exists auth_users (
                id uuid primary key,
                email text not null unique,
                password_hash text not null,
                created_at_utc timestamptz not null,
                roles text[] not null default '{}'
            );

            alter table auth_users
            add column if not exists roles text[] not null default '{}';

            create table if not exists auth_refresh_tokens (
                id uuid primary key,
                user_id uuid not null references auth_users(id) on delete cascade,
                token_hash text not null unique,
                created_at_utc timestamptz not null,
                expires_at_utc timestamptz not null,
                revoked_at_utc timestamptz null
            );

            create table if not exists auth_password_reset_tokens (
                id uuid primary key,
                user_id uuid not null references auth_users(id) on delete cascade,
                token_hash text not null unique,
                created_at_utc timestamptz not null,
                expires_at_utc timestamptz not null,
                consumed_at_utc timestamptz null
            );
            """);
        await command.ExecuteNonQueryAsync(cancellationToken);
    }
}
