import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import type { DesignApprovalMessage } from '@prisma/client';

export async function GET(
  req: Request,
  { params }: { params: { id: string } }
) {
  try {
    const messages = await prisma.designApprovalMessage.findMany({
      where: { designId: params.id },
      orderBy: { createdAt: 'asc' },
    });

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

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

    // Support both old format (sender/body) and new format (role/message/messageType)
    const finalSender = role || sender;
    const finalBody = message || body;
    const finalMessageType = messageType || 'MESSAGE';

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

    const created = await prisma.designApprovalMessage.create({
      data: {
        designId: params.id,
        sender: finalSender,
        body: finalBody,
        messageType: finalMessageType,
      },
    });

    return NextResponse.json(created);
  } catch (err) {
    console.error('Error creating message:', err);
    return NextResponse.json(
      { error: 'Failed to create message' },
      { status: 500 }
    );
  }
}
