export const dynamic = 'force-dynamic';
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

export async function GET() {
  try {
    const categories = await prisma.category.findMany({
      orderBy: { order: 'asc' },
      include: {
        _count: { select: { vehicles: true } },
        children: {
          orderBy: { order: 'asc' },
          include: { _count: { select: { vehicles: true } } },
        },
      },
    });
    return NextResponse.json(categories ?? []);
  } catch (error: any) {
    console.error('Categories GET error:', error);
    return NextResponse.json({ error: 'Failed to fetch' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const data = await request.json();
    const slug = (data?.name ?? 'category')
      .toLowerCase()
      .replace(/[^a-z0-9\s-]/g, '')
      .replace(/\s+/g, '-');

    const category = await prisma.category.create({
      data: {
        name: data?.name ?? '',
        nameEn: data?.nameEn ?? null,
        slug,
        description: data?.description ?? null,
        imageUrl: data?.imageUrl ?? null,
        order: data?.order ?? 0,
        parentId: data?.parentId ?? null,
      },
    });
    return NextResponse.json(category);
  } catch (error: any) {
    console.error('Category create error:', error);
    return NextResponse.json({ error: 'Failed to create' }, { status: 500 });
  }
}
