import { NextRequest, NextResponse } from 'next/server';
import { clonePermissionTemplateForOrganization } from '@/features/permission-management/server/permission-template-data';
import { AuthError, requireSuperAdminOrganizationAccess } from '@/lib/auth/session';

export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { organization, session } = await requireSuperAdminOrganizationAccess();
    const templateId = Number((await params).id);
    const body = (await request.json().catch(() => ({}))) as { reason?: string };
    const clonedId = await clonePermissionTemplateForOrganization({
      organizationId: organization.id,
      actorUserId: session.user.id,
      templateId,
      reason: body.reason
    });

    return NextResponse.json({
      success: true,
      message: 'Permission template cloned successfully',
      template_id: clonedId
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error && error.message === 'NOT_FOUND') {
      return NextResponse.json({ message: 'Permission template not found' }, { status: 404 });
    }

    return NextResponse.json({ message: 'Unable to clone permission template' }, { status: 500 });
  }
}
