import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import type { MessageDTO } from '@/lib/types';

export async function GET(_req: Request, { params }: { params: { id: string } }) {
  const rows = await prisma.message.findMany({
    where: { proofId: params.id },
    orderBy: { createdAt: 'asc' },
  });

  const messages: MessageDTO[] = rows.map((m) => ({
    id: m.id,
    proofId: m.proofId,
    sender: m.sender as MessageDTO['sender'],
    body: m.body,
    createdAt: m.createdAt.toISOString(),
  }));

  return NextResponse.json(messages);
}

export async function POST(req: Request, { params }: { params: { id: string } }) {
  const { sender, body } = await req.json();

  if (sender !== 'ADMIN' && sender !== 'CUSTOMER') {
    return NextResponse.json({ error: 'Invalid sender' }, { status: 400 });
  }
  const trimmed = String(body ?? '').trim();
  if (!trimmed) {
    return NextResponse.json({ error: 'Message body is required' }, { status: 400 });
  }

  const proof = await prisma.designProof.findUnique({ where: { id: params.id } });
  if (!proof) {
    return NextResponse.json({ error: 'Not found' }, { status: 404 });
  }

  const created = await prisma.message.create({
    data: { proofId: params.id, sender, body: trimmed },
  });

  const message: MessageDTO = {
    id: created.id,
    proofId: created.proofId,
    sender: created.sender as MessageDTO['sender'],
    body: created.body,
    createdAt: created.createdAt.toISOString(),
  };

  return NextResponse.json(message);
}
