// API Endpoint: GET /api/god/campaigns/status/[id]
import type { APIRoute } from 'astro';
import { pool } from '../../../../../lib/db';

export const GET: APIRoute = async ({ params, request }) => {
    try {
        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 { id } = params;

        // Get campaign details
        const campaignResult = await pool.query(
            `SELECT id, name, status, created_at, updated_at FROM campaign_masters WHERE id = $1`,
            [id]
        );

        if (campaignResult.rows.length === 0) {
            return new Response(JSON.stringify({ error: 'Campaign not found' }), {
                status: 404,
                headers: { 'Content-Type': 'application/json' }
            });
        }

        const campaign = campaignResult.rows[0];

        // Count generated posts
        const postsResult = await pool.query(
            `SELECT COUNT(*) as count FROM variation_registry WHERE campaign_id = $1`,
            [id]
        );

        const postsCreated = parseInt(postsResult.rows[0].count);

        // Get block usage stats
        const blockStats = await pool.query(
            `SELECT block_type, total_uses 
       FROM block_usage_stats 
       WHERE content_fragment_id IN (
         SELECT id FROM content_fragments WHERE campaign_id = $1
       )
       ORDER BY total_uses DESC
       LIMIT 10`,
            [id]
        );

        return new Response(JSON.stringify({
            campaignId: campaign.id,
            name: campaign.name,
            status: campaign.status,
            postsCreated,
            createdAt: campaign.created_at,
            updatedAt: campaign.updated_at,
            blockUsage: blockStats.rows
        }), {
            status: 200,
            headers: { 'Content-Type': 'application/json' }
        });

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