import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import {
  getTheme as getThemeViaService,
  updateTheme as updateThemeViaService,
  deleteTheme as deleteThemeViaService,
} 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 }>;
}

// GET /api/themes/[id] - Get a specific theme
export async function GET(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 getThemeViaService(jwt, id);
    return NextResponse.json(theme);
  } catch (error) {
    logError('Failed to get theme', error);
    return NextResponse.json({ error: 'Failed to fetch theme' }, { status: 500 });
  }
}

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

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