import type { APIRoute } from 'astro';
import { runMigrationFile, getMigrationStatus } from '@/lib/db/migrate';
import { readFile } from 'fs/promises';
import { join } from 'path';

/**
 * Schema Initialization Endpoint
 * Executes migration files with transactional safety
 */

function validateGodToken(request: Request): boolean {
    const token = request.headers.get('X-God-Token') ||
        request.headers.get('Authorization')?.replace('Bearer ', '') ||
        new URL(request.url).searchParams.get('token');

    const godToken = process.env.GOD_MODE_TOKEN || import.meta.env.GOD_MODE_TOKEN;
    if (!godToken) return true; // Dev mode
    return token === godToken;
}

export const POST: APIRoute = async ({ request }) => {
    if (!validateGodToken(request)) {
        return new Response(JSON.stringify({ error: 'Unauthorized' }), {
            status: 401,
            headers: { 'Content-Type': 'application/json' }
        });
    }

    try {
        // Read the main migration file
        const migrationPath = join(process.cwd(), 'migrations', '01_init_complete.sql');
        const sqlContent = await readFile(migrationPath, 'utf-8');

        // Run migrations in transaction
        const result = await runMigrationFile(sqlContent);

        if (!result.success) {
            return new Response(JSON.stringify({
                error: 'Migration failed',
                details: result.error,
                rolledBack: result.rolledBack,
                migrationsRun: result.migrationsRun
            }), {
                status: 500,
                headers: { 'Content-Type': 'application/json' }
            });
        }

        // Get final status
        const status = await getMigrationStatus();

        return new Response(JSON.stringify({
            success: true,
            message: '🔱 Database schema initialized successfully',
            migrationsRun: result.migrationsRun,
            tablesCreated: status.tables,
            timestamp: new Date().toISOString()
        }), {
            status: 200,
            headers: { 'Content-Type': 'application/json' }
        });

    } catch (error: any) {
        return new Response(JSON.stringify({
            error: 'Failed to read or execute migration file',
            details: error.message
        }), {
            status: 500,
            headers: { 'Content-Type': 'application/json' }
        });
    }
};

export const GET: APIRoute = async ({ request }) => {
    if (!validateGodToken(request)) {
        return new Response(JSON.stringify({ error: 'Unauthorized' }), {
            status: 401,
            headers: { 'Content-Type': 'application/json' }
        });
    }

    const status = await getMigrationStatus();

    return new Response(JSON.stringify({
        tables: status.tables,
        tableCount: status.tables.length,
        initialized: status.tables.length > 0
    }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
    });
};
