import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import {
  listThemes as listThemesViaService,
  createTheme as createThemeViaService,
} from '@/lib/platform-client';

function getJwt(req: NextRequest): string {
  const cookie = req.headers.get('cookie') ?? '';
  const match = cookie.match(/(?:^|;\s*)token=([^;]+)/);
  if (match) return match[1];
  return req.headers.get('authorization')?.replace('Bearer ', '') ?? '';
}

// GET /api/themes - List all themes (admin only)
export async function GET(request: NextRequest) {
  try {
    const jwt = getJwt(request);
    if (!jwt) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    const themes = await listThemesViaService(jwt);
    return NextResponse.json(themes);
  } catch (error) {
    logError('Failed to list themes', error);
    return NextResponse.json({ error: 'Failed to fetch themes' }, { status: 500 });
  }
}

// POST /api/themes - Create a new theme (admin only)
export async function POST(request: NextRequest) {
  try {
    const jwt = getJwt(request);
    if (!jwt) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    const body = await request.json();
    if (!body.name) {
      return NextResponse.json({ error: 'Theme name is required' }, { status: 400 });
    }
    const theme = await createThemeViaService(jwt, body);
    return NextResponse.json(theme, { status: 201 });
  } catch (error) {
    logError('Failed to create theme', error);
    return NextResponse.json({ error: 'Failed to create theme' }, { status: 500 });
  }
}
