import { DashboardMessageSendSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { MessageSendTimeoutError, sendDashboardMessageFromWebui } from '@/lib/module-configs/messages';
import { prisma } from '@/lib/prisma';

interface RouteParams {
  params: Promise<{ guildId: string }>;
}

export async function POST(request: NextRequest, { params }: RouteParams) {
  const { guildId } = await params;
  try {
    const session = await requireGuildAccess(guildId);
    const body = await request.json();
    const input = DashboardMessageSendSchema.parse(body);

    const result = await sendDashboardMessageFromWebui(guildId, session.user.id, input);

    await writeDashboardAudit(prisma, {
      guildId,
      actorUserId: session.user.id,
      action: 'messages.send',
      path: `/dashboard/${guildId}/messages`,
      after: {
        channelId: result.channelId,
        mode: input.mode,
        messageId: result.messageId,
        bindingId: result.bindingId
      }
    });

    return NextResponse.json(result, { status: 201 });
  } catch (error) {
    if (error instanceof MessageSendTimeoutError) {
      return NextResponse.json({ error: error.message }, { status: 504 });
    }
    return toApiErrorResponse(error);
  }
}
