import { z } from 'zod'
import { findOrganizationActionById, type Action as TopLevelAction } from './actions'
import { DisplayMetadataSchema, ModelIdSchema } from './shared'

export const ProspectingLifecycleStageSchema = DisplayMetadataSchema.extend({
  id: ModelIdSchema,
  order: z.number().min(0)
})

export const RecordColumnConfigSchema = z.object({
  key: ModelIdSchema,
  label: z.string().trim().min(1).max(120),
  path: z.string().trim().min(1).max(500),
  width: z.union([z.number().positive(), z.string().trim().min(1).max(100)]).optional(),
  renderType: z.enum(['text', 'badge', 'datetime', 'count', 'json']).optional(),
  badgeColor: z.string().trim().min(1).max(40).optional()
})

export const RecordColumnsConfigSchema = z
  .object({
    company: z.array(RecordColumnConfigSchema).optional(),
    contact: z.array(RecordColumnConfigSchema).optional()
  })
  .refine((columns) => Boolean(columns.company?.length || columns.contact?.length), {
    message: 'recordColumns must include at least one entity column set'
  })

export const CredentialRequirementSchema = z.object({
  key: ModelIdSchema,
  provider: ModelIdSchema,
  credentialType: z.enum(['api-key', 'api-key-secret', 'oauth', 'webhook-secret']),
  label: z.string().trim().min(1).max(120),
  required: z.boolean(),
  selectionMode: z.enum(['single', 'multiple']).optional(),
  inputPath: z.string().trim().min(1).max(500),
  verifyOnRun: z.boolean().optional()
})

export const ProspectingBuildTemplateStepSchema = DisplayMetadataSchema.extend({
  id: ModelIdSchema,
  primaryEntity: z.enum(['company', 'contact']),
  outputs: z.array(z.enum(['company', 'contact', 'export'])).min(1),
  stageKey: ModelIdSchema,
  recordEntity: z.enum(['company', 'contact']).optional(),
  recordsStageKey: ModelIdSchema.optional(),
  recordSourceStageKey: ModelIdSchema.optional(),
  dependsOn: z.array(ModelIdSchema).optional(),
  dependencyMode: z.literal('per-record-eligibility'),
  actionKey: ModelIdSchema,
  defaultBatchSize: z.number().int().positive(),
  maxBatchSize: z.number().int().positive(),
  recordColumns: RecordColumnsConfigSchema.optional(),
  credentialRequirements: z.array(CredentialRequirementSchema).optional()
}).refine((step) => step.defaultBatchSize <= step.maxBatchSize, {
  message: 'defaultBatchSize must be less than or equal to maxBatchSize',
  path: ['defaultBatchSize']
})

export const ProspectingBuildTemplateSchema = DisplayMetadataSchema.extend({
  id: ModelIdSchema,
  steps: z.array(ProspectingBuildTemplateStepSchema).min(1)
})

export type ListBuilderStep = z.infer<typeof ProspectingBuildTemplateStepSchema>
export type ProspectingBuildTemplate = z.infer<typeof ProspectingBuildTemplateSchema>
export type RecordColumnConfig = z.infer<typeof RecordColumnConfigSchema>
export type CredentialRequirement = z.infer<typeof CredentialRequirementSchema>
export type TemplateName = string
export type StepName = string
export type ActionRegistry = TopLevelAction[]

/**
 * Generic empty default for the action registry.
 * Tenant-specific lead-gen action lists belong in tenant Organization Models.
 */
export const ACTION_REGISTRY: ActionRegistry = []

export function findActionById(id: string): TopLevelAction | undefined {
  return findOrganizationActionById(id)
}
