import type {
  DocumentTemplateLifecycleStatus,
  DocumentTemplateVersionAuditSummary,
  DocumentTemplateVersionValidationSummary,
} from '../types';

export const CURRENT_TEMPLATE_RUNTIME_VERSION = 'p5.1-template-management';

export interface DocumentTemplateVisualSummary {
  status: 'PASS' | 'WARNING' | 'FAIL' | 'NOT_RUN';
  generatedAt: string | null;
  changedPages: number;
  layoutDifferences: number;
}

export interface DocumentTemplateManagementMetadata {
  lifecycleStatus?: DocumentTemplateLifecycleStatus;
  runtimeVersion?: string | null;
  templateVariant?: string | null;
  brand?: string | null;
  publishedAt?: string | null;
  publishedBy?: string | null;
  activatedAt?: string | null;
  activatedBy?: string | null;
  archivedAt?: string | null;
  archivedBy?: string | null;
  previousVersionId?: string | null;
  nextVersionId?: string | null;
  validatedAt?: string | null;
  validationSummary?: DocumentTemplateVersionValidationSummary | null;
  auditSummary?: DocumentTemplateVersionAuditSummary | null;
  visualSummary?: DocumentTemplateVisualSummary | null;
}

function getSchemaRecord(schemaJson: unknown): Record<string, unknown> {
  return schemaJson && typeof schemaJson === 'object'
    ? { ...(schemaJson as Record<string, unknown>) }
    : {};
}

export function getLegacyManagementMetadata(
  schemaJson: unknown,
): DocumentTemplateManagementMetadata {
  const schema = getSchemaRecord(schemaJson);
  const metadata = schema.__templateManagement;

  return metadata && typeof metadata === 'object'
    ? { ...(metadata as DocumentTemplateManagementMetadata) }
    : {};
}

export function getManagementMetadata(args: {
  metadataJson?: unknown;
  schemaJson?: unknown;
}): DocumentTemplateManagementMetadata {
  if (args.metadataJson && typeof args.metadataJson === 'object') {
    return { ...(args.metadataJson as DocumentTemplateManagementMetadata) };
  }

  return getLegacyManagementMetadata(args.schemaJson);
}

export function sanitizeTemplateSchemaJson(schemaJson: unknown): unknown {
  const schema = getSchemaRecord(schemaJson);

  if (!('__templateManagement' in schema)) {
    return schemaJson;
  }

  const { __templateManagement: _management, ...sanitized } = schema;
  return sanitized;
}

export function mergeManagementMetadata(args: {
  currentMetadataJson?: unknown;
  currentSchemaJson?: unknown;
  patch: DocumentTemplateManagementMetadata;
}): DocumentTemplateManagementMetadata {
  return {
    ...getManagementMetadata({
      metadataJson: args.currentMetadataJson,
      schemaJson: args.currentSchemaJson,
    }),
    ...args.patch,
  };
}
