import { NextRequest, NextResponse } from 'next/server';
import { activateDocumentLibraryVersion } from '@/features/foundation/document-library/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

type Params = { params: Promise<{ id: string }> };

export async function POST(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentLibraryActivate
    });
    const version = await activateDocumentLibraryVersion({
      versionId: id,
      organizationId: organization.id,
      userId: session.user.id
    });

    return NextResponse.json({
      success: true,
      message: 'Document library version activated successfully',
      version
    });
  } 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 document library version' },
      { status: 500 }
    );
  }
}
