import { z } from 'zod';

export const fleetSizeValues = ['1-9', '10-24', '25-49', '50-99', '100-249', '250+'] as const;
export const demoSourceValues = [
  'header',
  'mobile-header',
  'hero',
  'pricing',
  'final-cta',
  'footer',
] as const;

const compactText = (maximum: number) =>
  z
    .string()
    .transform((value) => value.trim().replace(/\s+/g, ' '))
    .pipe(z.string().min(1, 'required').max(maximum, 'too_long'));

const optionalCompactText = (maximum: number) =>
  z
    .string()
    .transform((value) => value.trim().replace(/\s+/g, ' '))
    .pipe(z.string().max(maximum, 'too_long'))
    .transform((value) => (value.length === 0 ? undefined : value))
    .optional();

export const demoLeadSchema = z
  .object({
    fullName: compactText(120),
    workEmail: z
      .string()
      .transform((value) => value.trim().toLowerCase())
      .pipe(
        z
          .string()
          .min(1, 'required')
          .max(254, 'too_long')
          .regex(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, 'invalid_email'),
      ),
    company: compactText(160),
    fleetSize: z.enum(fleetSizeValues, { message: 'invalid_fleet_size' }),
    market: optionalCompactText(100),
    preferredLanguage: z.enum(['en', 'fr', 'ar']).optional(),
    message: optionalCompactText(1_000),
    idempotencyKey: z.string().uuid('invalid_idempotency_key'),
    source: z.enum(demoSourceValues, { message: 'invalid_source' }),
  })
  .strict();

export const demoSubmissionEnvelopeSchema = z
  .object({
    lead: demoLeadSchema,
    guard: z
      .object({
        honeypot: z.string().max(200).default(''),
        startedAtMs: z.number().int().nonnegative(),
      })
      .strict(),
  })
  .strict();

export type DemoLeadInput = z.input<typeof demoLeadSchema>;
export type DemoLead = z.output<typeof demoLeadSchema>;
export type DemoSubmissionEnvelope = z.output<typeof demoSubmissionEnvelopeSchema>;
export type DemoSource = (typeof demoSourceValues)[number];

export type DemoFailureCategory =
  | 'validation'
  | 'consent'
  | 'duplicate'
  | 'rate-limit'
  | 'integration'
  | 'timeout'
  | 'configuration'
  | 'abuse';

export type DemoSubmissionResult =
  | {
      ok: true;
      submissionId: string;
      acceptedAt: string;
      nextAction: { type: 'success'; mode: 'local' };
    }
  | {
      ok: false;
      category: DemoFailureCategory;
      fieldErrors?: Record<string, string>;
      formErrorCode: string;
      retryable: boolean;
      correlationId?: string;
    };

export function zodFieldErrors(error: z.ZodError): Record<string, string> {
  const result: Record<string, string> = {};
  for (const issue of error.issues) {
    const path = issue.path.at(-1);
    if (typeof path !== 'string' || result[path]) continue;
    result[path] = issue.message;
  }
  return result;
}
