// API Endpoint: POST /api/god/campaigns/create
import type { APIRoute } from 'astro';
import { pool } from '../../../../lib/db';
import crypto from 'crypto';

interface CampaignBlueprint {
    asset_name: string;
    deployment_target: string;
    variables: Record<string, string>;
    content: {
        url_path: string;
        meta_description: string;
        body: Array<{
            block_type: string;
            content: string;
        }>;
    };
}

export const POST: APIRoute = async ({ request }) => {
    try {
        // Auth check
        const godToken = request.headers.get('X-God-Token');
        if (!godToken || godToken !== import.meta.env.GOD_TOKEN) {
            return new Response(JSON.stringify({ error: 'Unauthorized' }), {
                status: 401,
                headers: { 'Content-Type': 'application/json' }
            });
        }

        const body = await request.json();
        const { name, blueprint } = body as { name?: string; blueprint: CampaignBlueprint };

        if (!blueprint || !blueprint.content || !blueprint.variables) {
            return new Response(JSON.stringify({ error: 'Invalid blueprint structure' }), {
                status: 400,
                headers: { 'Content-Type': 'application/json' }
            });
        }

        const client = await pool.connect();

        try {
            await client.query('BEGIN');

            // Get admin site ID
            const siteResult = await client.query(
                `SELECT id FROM sites WHERE domain = 'spark.jumpstartscaling.com' LIMIT 1`
            );

            if (siteResult.rows.length === 0) {
                throw new Error('Admin site not found');
            }

            const siteId = siteResult.rows[0].id;

            // Insert campaign
            const campaignName = name || blueprint.asset_name;
            const campaignResult = await client.query(
                `INSERT INTO campaign_masters (site_id, name, blueprint_json, status)
         VALUES ($1, $2, $3, 'pending')
         RETURNING id`,
                [siteId, campaignName, JSON.stringify(blueprint)]
            );

            const campaignId = campaignResult.rows[0].id;

            // Insert content fragments (blocks)
            for (const block of blueprint.content.body) {
                const contentHash = crypto.createHash('sha256')
                    .update(block.content)
                    .digest('hex')
                    .substring(0, 32);

                await client.query(
                    `INSERT INTO content_fragments (
            site_id, campaign_id, block_type, blueprint_name, content, content_hash, use_count
          ) VALUES ($1, $2, $3, $4, $5, $6, 0)
          ON CONFLICT (content_hash) DO UPDATE SET
            campaign_id = EXCLUDED.campaign_id,
            use_count = content_fragments.use_count
          `,
                    [
                        siteId,
                        campaignId,
                        block.block_type.replace(/ \(\d+\)$/, ''),
                        campaignName,
                        block.content,
                        contentHash
                    ]
                );
            }

            await client.query('COMMIT');

            return new Response(JSON.stringify({
                success: true,
                campaignId,
                message: `Campaign "${campaignName}" created successfully. Use /launch/${campaignId} to generate content.`
            }), {
                status: 201,
                headers: { 'Content-Type': 'application/json' }
            });

        } catch (err) {
            await client.query('ROLLBACK');
            throw err;
        } finally {
            client.release();
        }

    } catch (error: any) {
        console.error('Campaign creation error:', error);
        return new Response(JSON.stringify({
            error: 'Campaign creation failed',
            details: error.message
        }), {
            status: 500,
            headers: { 'Content-Type': 'application/json' }
        });
    }
};
