import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { sendDesignSubmissionNotification } from '@/lib/mail';
import { getCurrentCustomer } from '@/lib/auth';

export async function POST(req: Request) {
  try {
    const customer = await getCurrentCustomer();
    if (!customer) {
      return NextResponse.json(
        { error: 'Must be logged in to submit design' },
        { status: 401 }
      );
    }

    const {
      productId,
      designJson,
      designPreviewUrl,
      designPreviewUrlBack,
      placementPreviewUrl,
      placementPreviewUrlBack,
      designWidthCm,
      designHeightCm,
      designImageDimensions,
      color,
      size,
    } = await req.json();

    if (!productId || !designJson) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      );
    }

    const product = await prisma.product.findUnique({
      where: { id: productId },
    });

    if (!product) {
      return NextResponse.json({ error: 'Product not found' }, { status: 404 });
    }

    const design = await prisma.designApproval.create({
      data: {
        customerId: customer.id,
        customerEmail: customer.email,
        customerName: customer.name,
        productId,
        designJson,
        designPreviewUrl,
        designPreviewUrlBack,
        placementPreviewUrl,
        placementPreviewUrlBack,
        designWidthCm: designWidthCm || null,
        designHeightCm: designHeightCm || null,
        designImageDimensions: designImageDimensions && designImageDimensions.length > 0 ? JSON.stringify(designImageDimensions) : null,
        color,
        size,
      },
    });

    const adminLink = `${process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'}/admin/designs/${design.id}`;
    await sendDesignSubmissionNotification({
      customerName,
      productName: product.name,
      adminLink,
    });

    return NextResponse.json(design);
  } catch (err) {
    console.error('Error submitting design:', err);
    return NextResponse.json(
      { error: 'Failed to submit design' },
      { status: 500 }
    );
  }
}
