import { ScheduledMessageDashboardCreateSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import {
  createScheduledMessageDashboard,
  listScheduledMessagesDashboard,
  SchedulerValidationError
} from '@/lib/module-configs/scheduler';
import { prisma } from '@/lib/prisma';

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

export async function GET(_request: NextRequest, { params }: RouteParams) {
  const { guildId } = await params;
  try {
    await requireGuildAccess(guildId);
    const schedules = await listScheduledMessagesDashboard(guildId);
    return NextResponse.json({ schedules });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

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 = ScheduledMessageDashboardCreateSchema.parse(body);

    const schedule = await createScheduledMessageDashboard(guildId, session.user.id, input);

    await writeDashboardAudit(prisma, {
      guildId,
      actorUserId: session.user.id,
      action: 'scheduler.create',
      path: `/dashboard/${guildId}/scheduler`,
      after: schedule
    });

    return NextResponse.json(schedule, { status: 201 });
  } catch (error) {
    if (error instanceof SchedulerValidationError) {
      return NextResponse.json({ error: error.code }, { status: 400 });
    }
    return toApiErrorResponse(error);
  }
}
