import { NextRequest, NextResponse } from 'next/server';
import { setPermissionTemplateActiveState } 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 };
    await setPermissionTemplateActiveState({
      organizationId: organization.id,
      actorUserId: session.user.id,
      templateId,
      isActive: true,
      reason: body.reason
    });

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

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

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