import { NextResponse } from 'next/server';
import { auditAction } from '@/features/foundation/audit-log/service';
import { validateAndPersistDocumentTemplateVersion } from '@/features/foundation/document-template/server/management-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: Request, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentTemplateUpdate,
    });
    const validation = await validateAndPersistDocumentTemplateVersion({
      versionId: id,
      organizationId: organization.id,
    });

    await auditAction({
      organizationId: organization.id,
      userId: session.user.id,
      entityType: 'crm_document_template_version',
      entityId: id,
      action: 'validate',
      afterData: validation,
    });

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