import type { APIRoute } from 'astro';
import Redis from 'ioredis';
import { SystemConfigSchema } from '@/lib/data/dataValidator';

/**
 * System Configuration Endpoint
 * Persistent settings in Redis
 */

const REDIS_URL = process.env.REDIS_URL || 'redis://redis:6379';
const CONFIG_KEY = 'god_mode:system_config';

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;
    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' }
        });
    }

    const redis = new Redis(REDIS_URL, {
        lazyConnect: true,
        enableOfflineQueue: false
    });

    try {
        const config = SystemConfigSchema.parse(await request.json());

        await redis.connect();

        // Store each config value in Redis hash
        await redis.hset(CONFIG_KEY, {
            throttle_delay_ms: config.throttle_delay_ms.toString(),
            max_concurrency: config.max_concurrency.toString(),
            max_cost_per_hour: config.max_cost_per_hour.toString(),
            enable_auto_throttle: config.enable_auto_throttle.toString(),
            memory_threshold_pct: config.memory_threshold_pct.toString(),
            updated_at: new Date().toISOString()
        });

        await redis.quit();

        return new Response(JSON.stringify({
            success: true,
            config,
            message: 'System configuration saved to Redis',
            timestamp: new Date().toISOString()
        }), {
            status: 200,
            headers: { 'Content-Type': 'application/json' }
        });

    } catch (error: any) {
        try { await redis.quit(); } catch { }

        return new Response(JSON.stringify({
            error: 'Configuration update failed',
            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 redis = new Redis(REDIS_URL, {
        lazyConnect: true,
        enableOfflineQueue: false
    });

    try {
        await redis.connect();
        const config = await redis.hgetall(CONFIG_KEY);
        await redis.quit();

        if (Object.keys(config).length === 0) {
            // Return defaults if not set
            return new Response(JSON.stringify({
                config: {
                    throttle_delay_ms: 0,
                    max_concurrency: 128,
                    max_cost_per_hour: 100,
                    enable_auto_throttle: true,
                    memory_threshold_pct: 90
                },
                source: 'defaults',
                message: 'No custom config found - showing defaults'
            }), {
                status: 200,
                headers: { 'Content-Type': 'application/json' }
            });
        }

        return new Response(JSON.stringify({
            config: {
                throttle_delay_ms: parseInt(config.throttle_delay_ms),
                max_concurrency: parseInt(config.max_concurrency),
                max_cost_per_hour: parseFloat(config.max_cost_per_hour),
                enable_auto_throttle: config.enable_auto_throttle === 'true',
                memory_threshold_pct: parseInt(config.memory_threshold_pct)
            },
            source: 'redis',
            updated_at: config.updated_at,
            timestamp: new Date().toISOString()
        }), {
            status: 200,
            headers: { 'Content-Type': 'application/json' }
        });

    } catch (error: any) {
        try { await redis.quit(); } catch { }

        return new Response(JSON.stringify({
            error: 'Failed to retrieve configuration',
            details: error.message
        }), {
            status: 500,
            headers: { 'Content-Type': 'application/json' }
        });
    }
};
