import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { sendDesignReadyForReview } from '@/lib/mail';

export async function POST(
  req: Request,
  { params }: { params: { id: string } }
) {
  try {
    const design = await prisma.designApproval.findUnique({
      where: { id: params.id },
      include: { product: true },
    });

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

    // Update status to IN_REVIEW
    const updated = await prisma.designApproval.update({
      where: { id: params.id },
      data: { status: 'IN_REVIEW' },
      include: { product: true, messages: { orderBy: { createdAt: 'asc' } } },
    });

    // Send email to customer
    await sendDesignReadyForReview({
      customerName: design.customerName || 'Customer',
      customerEmail: design.customerEmail,
      productName: design.product.name,
      reviewLink: `${process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'}/designs/${params.id}/review`,
    });

    return NextResponse.json(updated);
  } catch (err) {
    console.error('Error sending design to customer:', err);
    return NextResponse.json(
      { error: 'Failed to send design' },
      { status: 500 }
    );
  }
}
