import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import { activateTheme as activateThemeViaService } 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 ', '') ?? '';
}

interface RouteParams {
  params: Promise<{ id: string }>;
}

// POST /api/themes/[id]/activate - Set a theme as active
export async function POST(request: NextRequest, { params }: RouteParams) {
  try {
    const jwt = getJwt(request);
    if (!jwt) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    const { id } = await params;
    const theme = await activateThemeViaService(jwt, id);
    return NextResponse.json(theme);
  } catch (error) {
    logError('Failed to activate theme', error);
    return NextResponse.json({ error: 'Failed to activate theme' }, { status: 500 });
  }
}
