import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { updateConversationSchema } from '@server/validators/conversations.validator';
import { getConversation, updateConversationStatus, appendMessage, markConversationRead, assignConversation, takeOverConversation, deleteConversation } from '@server/services/conversations.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    const conversation = await getConversation(id, req.session.restaurantId!);
    return NextResponse.json({ conversation });
  })
);

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateConversationSchema, async (req, ctx: RouteContext) => {
      const { id } = await ctx.params;
      const body = req.parsedBody;

      if (body.unread_count === 0) {
        const conversation = await markConversationRead(id, req.session.restaurantId!);
        return NextResponse.json({ conversation });
      }

      if (body.messages && body.messages.length > 0) {
        const msg = body.messages[0];
        const conversation = await appendMessage(id, req.session.restaurantId!, msg);
        return NextResponse.json({ conversation });
      }

      if (body.status === 'human' && body.assigned_agent) {
        const conversation = await takeOverConversation(id, req.session.restaurantId!, body.assigned_agent);
        return NextResponse.json({ conversation });
      }

      if (body.status) {
        const conversation = await updateConversationStatus(id, req.session.restaurantId!, body.status);
        return NextResponse.json({ conversation });
      }

      if (body.assigned_agent !== undefined) {
        const conversation = await assignConversation(id, req.session.restaurantId!, body.assigned_agent ?? null);
        return NextResponse.json({ conversation });
      }

      return NextResponse.json({ error: 'No valid action specified' }, { status: 400 });
    })
  )
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    await deleteConversation(id, req.session.restaurantId!);
    return NextResponse.json({ success: true });
  })
);
