import { TagDashboardUpdateSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { deleteTag, TagConflictError, updateTag } from '@/lib/module-configs/tags';
import { prisma } from '@/lib/prisma';

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

export async function PATCH(request: NextRequest, { params }: RouteParams) {
  const { guildId, tagId } = await params;
  try {
    const session = await requireGuildAccess(guildId);
    const body = await request.json();
    const patch = TagDashboardUpdateSchema.parse(body);

    const updated = await updateTag(guildId, tagId, patch);
    if (!updated) {
      return NextResponse.json({ error: 'Tag not found' }, { status: 404 });
    }

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

    return NextResponse.json(updated);
  } catch (error) {
    if (error instanceof TagConflictError) {
      return NextResponse.json({ error: error.message }, { status: 409 });
    }
    return toApiErrorResponse(error);
  }
}

export async function DELETE(_request: NextRequest, { params }: RouteParams) {
  const { guildId, tagId } = await params;
  try {
    const session = await requireGuildAccess(guildId);
    const deleted = await deleteTag(guildId, tagId);
    if (!deleted) {
      return NextResponse.json({ error: 'Tag not found' }, { status: 404 });
    }

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

    return NextResponse.json({ ok: true });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}
