import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { z } from 'zod';

const productSchema = z.object({
  name: z.string().min(2),
  nameAr: z.string().min(2),
  description: z.string().min(10),
  descriptionAr: z.string().min(10),
  price: z.number().positive(),
  oldPrice: z.number().positive().optional(),
  stock: z.number().int().nonnegative(),
  image: z.string().url(),
  images: z.array(z.string().url()).optional(),
  brand: z.string().min(2),
  categoryId: z.string()
});

export async function GET(req: Request) {
  try {
    const { searchParams } = new URL(req.url);
    const categoryId = searchParams.get('category');
    
    let products;
    if (categoryId) {
      products = await prisma.product.findMany({ where: { categoryId } });
    } else {
      products = await prisma.product.findMany();
    }
    
    return NextResponse.json({ success: true, products });
  } catch (error: any) {
    return NextResponse.json({ success: false, message: error.message }, { status: 500 });
  }
}

export async function POST(req: Request) {
  try {
    const body = await req.json();
    const validatedData = productSchema.parse(body);
    
    const product = await prisma.product.create({
      data: validatedData
    });
    
    return NextResponse.json({ success: true, product }, { status: 201 });
  } catch (error: any) {
    if (error instanceof z.ZodError) {
      return NextResponse.json({ success: false, message: 'Validation error', errors: error.flatten() }, { status: 400 });
    }
    return NextResponse.json({ success: false, message: error.message }, { status: 500 });
  }
}

export const dynamic = 'force-dynamic';
