import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditUpdate } from '@/features/foundation/audit-log/service';
import {
  setDocumentTemplateVersionActive,
  updateDocumentTemplateVersion
} from '@/features/foundation/document-template/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

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

const versionSchema = z.object({
  version: z.string().min(1).optional(),
  filePath: z.string().optional().nullable(),
  schemaJson: z.unknown().optional(),
  previewImageUrl: z.string().optional().nullable(),
  isActive: z.boolean().optional()
});

export async function PATCH(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentTemplateUpdate
    });
    const payload = versionSchema.parse(await request.json());

    if (Object.keys(payload).length === 1 && typeof payload.isActive === 'boolean') {
      const result = await setDocumentTemplateVersionActive(id, organization.id, payload.isActive);

      await auditUpdate({
        organizationId: organization.id,
        userId: session.user.id,
        entityType: 'crm_document_template_version',
        entityId: id,
        beforeData: result.before,
        afterData: result.after
      });

      return NextResponse.json({
        success: true,
        message: 'Document template version status updated successfully'
      });
    }

    const updated = await updateDocumentTemplateVersion(id, organization.id, payload);

    await auditUpdate({
      organizationId: organization.id,
      userId: session.user.id,
      entityType: 'crm_document_template_version',
      entityId: id,
      afterData: updated
    });

    return NextResponse.json({
      success: true,
      message: 'Document template version updated successfully'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { message: error.issues[0]?.message ?? 'Invalid payload' },
        { status: 400 }
      );
    }
    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }
    return NextResponse.json(
      { message: 'Unable to update document template version' },
      { status: 500 }
    );
  }
}
