using Dapper;
using QuantEngine.Core.Interfaces;
using QuantEngine.Infrastructure.Data;

namespace QuantEngine.Infrastructure.Repositories;

public sealed class CollectionSchemaInitializer : ICollectionSchemaInitializer
{
    private readonly IDbConnectionFactory _connectionFactory;

    public CollectionSchemaInitializer(IDbConnectionFactory connectionFactory)
    {
        _connectionFactory = connectionFactory;
    }

    public async Task InitializeAsync()
    {
        using var conn = _connectionFactory.CreateConnection();
        await conn.ExecuteAsync(@"
            CREATE TABLE IF NOT EXISTS quantengine.kis_collection_runs (
                run_id TEXT PRIMARY KEY,
                status TEXT NOT NULL,
                started_at TEXT NOT NULL,
                finished_at TEXT,
                total_snapshots INTEGER,
                total_errors INTEGER,
                updated_at TEXT NOT NULL
            );

            CREATE TABLE IF NOT EXISTS quantengine.kis_collection_snapshots (
                run_id TEXT NOT NULL,
                dataset_name TEXT,
                ticker TEXT NOT NULL,
                source_name TEXT NOT NULL,
                payload_json TEXT NOT NULL,
                captured_at TEXT NOT NULL,
                created_at TEXT NOT NULL,
                PRIMARY KEY (run_id, ticker, source_name)
            );

            CREATE TABLE IF NOT EXISTS quantengine.kis_collection_errors (
                id SERIAL PRIMARY KEY,
                run_id TEXT NOT NULL,
                source_name TEXT NOT NULL,
                error_kind TEXT NOT NULL,
                error_message TEXT,
                ticker TEXT,
                created_at TEXT NOT NULL
            );

            CREATE INDEX IF NOT EXISTS idx_kis_runs_started_at ON quantengine.kis_collection_runs(started_at DESC);
            CREATE INDEX IF NOT EXISTS idx_kis_snapshots_ticker ON quantengine.kis_collection_snapshots(ticker);
            CREATE INDEX IF NOT EXISTS idx_kis_snapshots_captured_at ON quantengine.kis_collection_snapshots(captured_at DESC);
            CREATE INDEX IF NOT EXISTS idx_kis_errors_run_id ON quantengine.kis_collection_errors(run_id);
        ");
    }
}
