import type { APIRoute } from 'astro';

/**
 * Media Templates API
 * Stub endpoint for Image Template Editor
 */

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

const DEFAULT_SVG = `<svg width="1200" height="630" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">
      <stop offset="0%" style="stop-color:#1e3a8a"/>
      <stop offset="100%" style="stop-color:#7c3aed"/>
    </linearGradient>
  </defs>
  <rect width="100%" height="100%" fill="url(#bg)"/>
  <text x="60" y="280" font-family="Arial, sans-serif" font-size="64" font-weight="bold" fill="white">{title}</text>
  <text x="60" y="360" font-family="Arial, sans-serif" font-size="28" fill="rgba(255,255,255,0.8)">{subtitle}</text>
  <text x="60" y="580" font-family="Arial, sans-serif" font-size="20" fill="rgba(255,255,255,0.6)">{site_name} • {city}, {state}</text>
</svg>`;

// In-memory storage (replace with DB later)
const templates = [
    {
        id: '1',
        name: 'Default Blue Gradient',
        svg_source: DEFAULT_SVG,
        is_default: true
    }
];

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({ templates }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
    });
};

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 body = await request.json();
        const newTemplate = {
            id: String(templates.length + 1),
            name: body.name,
            svg_source: body.svg_source || DEFAULT_SVG,
            is_default: false
        };
        templates.push(newTemplate);

        return new Response(JSON.stringify({ template: newTemplate }), {
            status: 201,
            headers: { 'Content-Type': 'application/json' }
        });
    } catch (error: any) {
        return new Response(JSON.stringify({ error: error.message }), {
            status: 500,
            headers: { 'Content-Type': 'application/json' }
        });
    }
};
