import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { sendDesignApprovedEmail } 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 });
    }

    const updated = await prisma.designApproval.update({
      where: { id: params.id },
      data: { status: 'APPROVED' },
      include: { product: true },
    });

    const checkoutLink = `${process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'}/made-to-order/${design.product.slug}?design=${design.id}`;
    await sendDesignApprovedEmail({
      to: design.customerEmail,
      customerName: design.customerName,
      productName: design.product.name,
      checkoutLink,
    });

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