import { TagDashboardCreateSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { createTag, listTags, TagConflictError, TagPremiumError } from '@/lib/module-configs/tags';
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 tags = await listTags(guildId);
    return NextResponse.json({ tags });
  } 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 = TagDashboardCreateSchema.parse(body);

    const tag = await createTag(guildId, session.user.id, input);

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

    return NextResponse.json(tag, { status: 201 });
  } catch (error) {
    if (error instanceof TagConflictError) {
      return NextResponse.json({ error: error.message }, { status: 409 });
    }
    if (error instanceof TagPremiumError) {
      return NextResponse.json({ error: error.code }, { status: 403 });
    }
    return toApiErrorResponse(error);
  }
}
