import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { Prisma } from '@prisma/client';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const category = searchParams.get('category');
    const search = searchParams.get('search');
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '10');

    const where: Prisma.ProductWhereInput = {
      isAvailable: true,
    };

    if (category) where.category = category;
    if (search) {
      where.OR = [
        { title: { contains: search } },
        { description: { contains: search } },
      ];
    }

    const skip = (page - 1) * limit;

    const [products, total] = await Promise.all([
      db.product.findMany({
        where,
        include: {
          seller: {
            select: { id: true, name: true, avatar: true },
          },
        },
        orderBy: { createdAt: 'desc' },
        skip,
        take: limit,
      }),
      db.product.count({ where }),
    ]);

    return NextResponse.json({
      products,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error('Products GET error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      title,
      description,
      price,
      discount,
      category,
      subcategory,
      images,
      stock,
      unit,
      sellerId,
    } = body;

    if (!title || !description || !price || !sellerId) {
      return NextResponse.json(
        { error: 'Missing required fields: title, description, price, sellerId' },
        { status: 400 }
      );
    }

    const product = await db.product.create({
      data: {
        title,
        description,
        price: parseFloat(String(price)),
        discount: discount ? parseFloat(String(discount)) : 0,
        category: category || 'daily_needs',
        subcategory: subcategory || null,
        images: images ? JSON.stringify(images) : '[]',
        stock: stock ? parseInt(String(stock)) : 1,
        unit: unit || null,
        sellerId,
      },
      include: {
        seller: {
          select: { id: true, name: true, avatar: true },
        },
      },
    });

    return NextResponse.json({ product }, { status: 201 });
  } catch (error) {
    console.error('Products POST error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
