import { z } from 'zod'

export const EntityFieldSchema = z.object({
  name: z.string().min(1),
  type: z.string().min(1),
  required: z.boolean().default(true),
  maxLength: z.number().optional(),
  description: z.string().optional(),
  isKey: z.boolean().default(false),
  indexed: z.boolean().default(false),
  /**
   * Optional C# expression marking this field as a computed (derived) attribute.
   * The Domain entity SKIPS the property entirely — the value lives only in the
   * read DTOs (ListDto / DetailDto) where scaffold-business injects the formula
   * into the LINQ projection. The EF Configuration also ignores the field.
   * See `scaffold-business/types.ts` and `audit-data-model` rule DM-016.
   */
  formula: z.string().optional(),
})

export const EntityRelationSchema = z.object({
  type: z.enum(['one-to-many', 'many-to-one', 'many-to-many', 'one-to-one']),
  targetEntity: z.string().min(1),
  /** FK column on the OWNING side (many-to-one / one-to-one). Default `${targetEntity}Id`. */
  foreignKey: z.string().optional(),
  /** Navigation property name. Default = targetEntity (reference) / `${targetEntity}s` (collection). */
  navigationName: z.string().optional(),
  nullable: z.boolean().default(false),
  /**
   * Referential action mirroring the BA data-model cascade vocabulary
   * (`create-data-model/levels/relationships.md`). Maps to EF Core
   * `DeleteBehavior`: restrict→Restrict, cascade→Cascade, set-null→SetNull,
   * no-action→NoAction. When omitted, falls back to the legacy `cascadeDelete`
   * boolean (true→cascade, false→restrict). Default effective behavior: restrict.
   */
  onDelete: z.enum(['restrict', 'cascade', 'set-null', 'no-action']).optional(),
  /** @deprecated Legacy boolean — prefer `onDelete`. Honored only when `onDelete` is absent. */
  cascadeDelete: z.boolean().default(false),
})

export const ScaffoldEntityInputSchema = z.object({
  name: z.string().min(1).regex(/^[A-Z][A-Za-z0-9]*$/),
  pluralName: z.string().optional(),
  module: z.string().min(1),
  appCode: z.string().min(1),
  domainPrefix: z.string().min(1).regex(/^[a-z][a-z0-9]*$/, 'domainPrefix must be lowercase alphanumeric'),
  namespace: z.string().optional(),
  tenantMode: z.enum(['strict', 'optional', 'none']).default('strict'),
  schemaTarget: z.enum(['core', 'extensions']).default('extensions'),
  fields: z.array(EntityFieldSchema).min(1),
  relations: z.array(EntityRelationSchema).default([]),
  constraints: z.array(z.string()).default([]),
  projectPath: z.string().min(1),
})

export type EntityField = z.infer<typeof EntityFieldSchema>
export type EntityRelation = z.infer<typeof EntityRelationSchema>
export type ScaffoldEntityInput = z.infer<typeof ScaffoldEntityInputSchema>
export interface GeneratedFile { path: string; content: string }
export interface ValidationResult { valid: boolean; errors: string[]; warnings: string[] }
