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

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

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

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

export async function PATCH(
  req: Request,
  { params }: { params: { id: string } }
) {
  try {
    const customer = await getCurrentCustomer();
    if (!customer) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { status } = await req.json();

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

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

export async function DELETE(
  req: Request,
  { params }: { params: { id: string } }
) {
  try {
    // Delete associated messages first
    await prisma.designApprovalMessage.deleteMany({
      where: { designApprovalId: params.id },
    });

    // Delete the design approval
    await prisma.designApproval.delete({
      where: { id: params.id },
    });

    return NextResponse.json({ success: true });
  } catch (err) {
    console.error('Error deleting design:', err);
    return NextResponse.json(
      { error: 'Failed to delete design' },
      { status: 500 }
    );
  }
}
