import type { APIRoute } from 'astro';

/**
 * Sh im Preview - SQL Dry Run
 * Translate Directus SDK queries to SQL without executing
 */

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

/**
 * Basic Directus query to SQL translation
 * This is a simplified version - full implementation in client.ts
 */
function translateToSQL(collection: string, query: any): string {
    const parts: string[] = [`SELECT *  FROM "${collection}"`];

    // WHERE clause from filter
    if (query.filter) {
        const conditions = buildConditions(query.filter);
        if (conditions) {
            parts.push(`WHERE ${conditions}`);
        }
    }

    // LIMIT
    if (query.limit) {
        parts.push(`LIMIT ${query.limit}`);
    }

    // OFFSET
    if (query.offset) {
        parts.push(`OFFSET ${query.offset}`);
    }

    return parts.join(' ');
}

function buildConditions(filter: any): string {
    const conditions: string[] = [];

    for (const [field, value] of Object.entries(filter)) {
        if (field === '_or') {
            const orConditions = (value as any[]).map(buildConditions).filter(Boolean);
            if (orConditions.length > 0) {
                conditions.push(`(${orConditions.join(' OR ')})`);
            }
            continue;
        }

        if (field === '_and') {
            const andConditions = (value as any[]).map(buildConditions).filter(Boolean);
            if (andConditions.length > 0) {
                conditions.push(`(${andConditions.join(' AND ')})`);
            }
            continue;
        }

        // Handle operators
        if (typeof value === 'object' && value !== null) {
            for (const [op, val] of Object.entries(value)) {
                switch (op) {
                    case '_eq':
                        conditions.push(`"${field}" = '${val}'`);
                        break;
                    case '_neq':
                        conditions.push(`"${field}" != '${val}'`);
                        break;
                    case '_gt':
                        conditions.push(`"${field}" > ${val}`);
                        break;
                    case '_lt':
                        conditions.push(`"${field}" < ${val}`);
                        break;
                    case '_contains':
                        conditions.push(`"${field}" ILIKE '%${val}%'`);
                        break;
                    case '_in':
                        const vals = (val as any[]).map(v => `'${v}'`).join(', ');
                        conditions.push(`"${field}" IN (${vals})`);
                        break;
                }
            }
        } else {
            // Simple equality
            conditions.push(`"${field}" = '${value}'`);
        }
    }

    return conditions.join(' AND ');
}

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

    try {
        const { collection, query } = await request.json();

        if (!collection) {
            return new Response(JSON.stringify({
                error: 'Missing collection name'
            }), {
                status: 400,
                headers: { 'Content-Type': 'application/json' }
            });
        }

        // Translate to SQL
        const sql = translateToSQL(collection, query || {});

        return new Response(JSON.stringify({
            collection,
            query: query || {},
            sql,
            executed: false,
            note: 'This is a dry-run preview only. Use POST /api/god/sql to execute.'
        }), {
            status: 200,
            headers: { 'Content-Type': 'application/json' }
        });

    } catch (error: any) {
        return new Response(JSON.stringify({
            error: 'Translation 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' }
        });
    }

    return new Response(JSON.stringify({
        endpoint: 'POST /api/god/shim/preview',
        description: 'Preview SQL translation without executing',
        usage: {
            example: {
                collection: 'posts',
                query: {
                    filter: {
                        status: { _eq: 'published' },
                        title: {
                            _contains: 'Austin'
                        }
                    },
                    limit: 10
                }
            }
        }
    }, null, 2), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
    });
};
