import { z } from 'zod'
import { DescriptionSchema, IconNameSchema, LabelSchema } from '../domains/shared'
import { OrganizationModelSchema } from '../schema'

export const OrganizationGraphNodeKindSchema = z.enum([
  'organization',
  'system',
  'client',
  'role',
  'action',
  'entity',
  'event',
  'policy',
  'stage',
  'resource',
  'knowledge',
  'customer-segment',
  'offering',
  'goal',
  'surface',
  'navigation-group',
  // Ontology records are projected from compiled System.ontology scopes.
  'ontology'
])

export const OrganizationGraphEdgeKindSchema = z.enum([
  'contains',
  'references',
  'maps_to',
  'uses',
  'governs',
  'links',
  'affects',
  'emits',
  'originates_from',
  'triggers',
  'approval',
  'applies_to',
  'effects',
  'actions',
  'reads',
  'writes',
  'uses_catalog'
])

export const OrganizationGraphNodeSchema = z.object({
  id: z.string().trim().min(1).max(400),
  kind: OrganizationGraphNodeKindSchema,
  label: LabelSchema,
  sourceId: z.string().trim().min(1).max(400).optional(),
  description: DescriptionSchema.optional(),
  icon: IconNameSchema.optional(),
  enabled: z.boolean().optional(),
  ontologyKind: z.string().trim().min(1).max(80).optional(),
  resourceType: z
    .enum(['workflow', 'agent', 'trigger', 'integration', 'external', 'human_checkpoint', 'script'])
    .optional()
})

export const OrganizationGraphEdgeSchema = z.object({
  id: z.string().trim().min(1).max(900),
  kind: OrganizationGraphEdgeKindSchema,
  sourceId: z.string().trim().min(1).max(400),
  targetId: z.string().trim().min(1).max(400),
  label: z.string().trim().min(1).max(120).optional(),
  relationshipType: z.enum(['triggers', 'uses', 'approval']).optional()
})

export const OrganizationGraphSchema = z.object({
  version: z.literal(1),
  organizationModelVersion: OrganizationModelSchema.shape.version,
  nodes: z.array(OrganizationGraphNodeSchema),
  edges: z.array(OrganizationGraphEdgeSchema)
})

export const BuildOrganizationGraphInputSchema = z.object({
  organizationModel: OrganizationModelSchema,
  commandViewData: z.unknown().optional()
})
