import { z } from 'zod'
import { OrganizationModelIconTokenSchema } from '../icons'

export const ModelIdSchema = z
  .string()
  .trim()
  .min(1)
  .max(100)
  .regex(/^[a-z0-9]+(?:[-._][a-z0-9]+)*$/, 'IDs must be lowercase and use -, _, or . separators')

export const LabelSchema = z.string().trim().min(1).max(120)
export const DescriptionSchema = z.string().trim().min(1).max(2000)
export const ColorTokenSchema = z.string().trim().min(1).max(50)
export const IconNameSchema = OrganizationModelIconTokenSchema
export const PathSchema = z.string().trim().startsWith('/').max(300)

export const ReferenceIdsSchema = z.array(ModelIdSchema).default([])

export const DisplayMetadataSchema = z.object({
  label: LabelSchema,
  description: DescriptionSchema.optional(),
  color: ColorTokenSchema.optional(),
  icon: IconNameSchema.optional()
})

// ---------------------------------------------------------------------------
// TechStack subsection — optional extension on a ResourceMapping entry that
// captures external-SaaS integration metadata: which platform, its purpose,
// credential health, and whether it is the system of record for its domain.
// Backward-compatible: existing entries without this key parse cleanly.
// ---------------------------------------------------------------------------

export const TechStackEntrySchema = z.object({
  /** Name of the external platform (e.g. "HubSpot", "Stripe", "Notion"). */
  platform: z.string().trim().min(1).max(200),
  /** Free-form description of what this integration is used for. */
  purpose: z.string().trim().min(1).max(500),
  /**
   * Health of the credential backing this integration.
   * - configured: credential present and valid
   * - pending: not yet set up
   * - expired: credential existed but has lapsed
   * - missing: expected but not present
   */
  credentialStatus: z.enum(['configured', 'pending', 'expired', 'missing']),
  /**
   * Whether this integration is the primary system of record for its domain
   * (e.g. HubSpot is SoR for contacts). Defaults to false.
   */
  isSystemOfRecord: z.boolean().default(false)
})

export const ResourceMappingSchema = DisplayMetadataSchema.extend({
  id: ModelIdSchema,
  resourceId: z.string().trim().min(1).max(255),
  resourceType: z.enum(['workflow', 'agent', 'trigger', 'integration', 'external', 'human_checkpoint']),
  systemIds: ReferenceIdsSchema,
  entityIds: ReferenceIdsSchema,
  surfaceIds: ReferenceIdsSchema,
  actionIds: ReferenceIdsSchema,
  /** Optional tech-stack metadata for external-SaaS integrations. */
  techStack: TechStackEntrySchema.optional()
})
