/**
 * Zod validation schemas for the customers module.
 * Shared between zync-api route handlers and zync-app React forms.
 * Importable from both packages via their respective build paths.
 */
import { z } from 'zod'

export const addressSchema = z
  .object({
    street: z.string().optional(),
    city: z.string().optional(),
    state: z.string().optional(),
    zip: z.string().optional(),
    country: z.string().optional(),
  })
  .partial()

export const createCustomerSchema = z.object({
  name: z.string().min(1),
  company: z.string().optional(),
  email: z.string().email().optional(),
  phone: z.string().optional(),
  address: addressSchema.optional(),
  notes: z.string().optional(),
})

export const updateCustomerSchema = createCustomerSchema.partial()

export const contactSchema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  phone: z.string().optional(),
  role: z.string().optional(),
  isPrimary: z.boolean().optional(),
})

export const createCommunicationSchema = z
  .preprocess((raw) => {
    if (raw && typeof raw === 'object' && 'to_address' in raw && !('toAddress' in raw)) {
      const { to_address, ...rest } = raw as Record<string, unknown>
      return { ...rest, toAddress: to_address }
    }
    return raw
  }, z.object({
    direction: z.enum(['outbound', 'internal']),
    channel: z.enum(['email', 'note']),
    subject: z.string().optional(),
    body: z.string().min(1),
    toAddress: z.string().email().optional(),
  }))
  .refine((d) => d.direction !== 'outbound' || (d.channel === 'email' && !!d.toAddress), {
    message: 'outbound email requires channel=email and to_address',
  })

export type CreateCustomerInput = z.infer<typeof createCustomerSchema>
export type UpdateCustomerInput = z.infer<typeof updateCustomerSchema>
export type ContactInput = z.infer<typeof contactSchema>
export type CreateCommunicationInput = z.infer<typeof createCommunicationSchema>
export type AddressInput = z.infer<typeof addressSchema>
