import { z } from 'zod';

import { baseListQuerySchema } from '@/lib/api/list-query';
import { PIPELINE_STAGES, LEAD_CATEGORIES } from '@/lib/constants';
import {
  optionalCountryIsoSchema,
  optionalPhoneE164Schema,
  optionalSubdivisionIsoSchema,
} from '@/lib/validators/i18n';

// ─── Create ──────────────────────────────────────────────────────────────────

/**
 * Desired-dimension input. Strings/numbers are coerced to a positive
 * decimal (string-typed for postgres `numeric` column compatibility);
 * empty strings collapse to `undefined` so a blank form field doesn't
 * round-trip "" → numeric error on the API.
 */
// In Zod 4, the optional() marker must live at the *outside* of the
// chain to propagate the field's optional-ness into the parent z.object.
// In v3 the same pattern worked with optional() in the middle, but v4's
// new ZodPipe (transform) doesn't forward optional through the pipe.
const optionalDesiredDimSchema = z
  .union([z.string(), z.number()])
  .transform((v) => {
    if (v === '') return undefined;
    const n = typeof v === 'number' ? v : parseFloat(v);
    if (!Number.isFinite(n) || n <= 0) return undefined;
    return String(Math.round(n * 100) / 100);
  })
  .optional();

const desiredUnitSchema = z.enum(['ft', 'm']).optional();

export const createInterestSchema = z.object({
  clientId: z.string().min(1),
  yachtId: z.string().optional(),
  berthId: z.string().optional(),
  /** Sales rep who owns this deal. Empty string treated as "unassign";
   *  omitting the field leaves the current assignment unchanged. On create,
   *  omitting falls back to system_settings.default_new_interest_owner. */
  assignedTo: z.string().nullable().optional(),
  /** Captured at reservation-agreement time. Drives the deposit-paid
   *  auto-advance once payment totals catch up. */
  depositExpectedAmount: z.string().optional().nullable(),
  depositExpectedCurrency: z.string().length(3).optional(),
  /** Doc sub-status badges. Stamped automatically by the Documenso webhook
   *  + custom-upload pathway; exposed via the update endpoint so reps can
   *  "Mark signed manually" from the milestone strip when a doc was signed
   *  outside the Documenso flow (e.g. an in-person paper signing). */
  eoiDocStatus: z.enum(['pending', 'sent', 'signed', 'declined', 'voided']).nullable().optional(),
  reservationDocStatus: z
    .enum(['pending', 'sent', 'signed', 'declined', 'voided'])
    .nullable()
    .optional(),
  contractDocStatus: z
    .enum(['pending', 'sent', 'signed', 'declined', 'voided'])
    .nullable()
    .optional(),
  /** Milestone dates exposed for manual stamping via PATCH; auto-stamped
   *  by the signing flows when reps use the Documenso pathway. Coerced
   *  to a Date so Drizzle gets the right type for the timestamptz column. */
  dateEoiSent: z.coerce.date().nullable().optional(),
  dateEoiSigned: z.coerce.date().nullable().optional(),
  dateReservationSigned: z.coerce.date().nullable().optional(),
  dateDepositReceived: z.coerce.date().nullable().optional(),
  dateContractSent: z.coerce.date().nullable().optional(),
  dateContractSigned: z.coerce.date().nullable().optional(),
  pipelineStage: z.enum(PIPELINE_STAGES).default('enquiry'),
  leadCategory: z.enum(LEAD_CATEGORIES).optional(),
  source: z.string().optional(),
  tagIds: z.array(z.string()).optional().default([]),
  // Omitting reminderEnabled / reminderDays falls back to the per-port
  // defaults configured at /admin/reminders (resolved in
  // createInterest). To opt out explicitly pass false / null.
  reminderEnabled: z.boolean().optional(),
  reminderDays: z.number().int().min(1).optional(),
  desiredLengthFt: optionalDesiredDimSchema,
  desiredWidthFt: optionalDesiredDimSchema,
  desiredDraftFt: optionalDesiredDimSchema,
  desiredLengthM: optionalDesiredDimSchema,
  desiredWidthM: optionalDesiredDimSchema,
  desiredDraftM: optionalDesiredDimSchema,
  desiredLengthUnit: desiredUnitSchema,
  desiredWidthUnit: desiredUnitSchema,
  desiredDraftUnit: desiredUnitSchema,
  /** Toggle: when true and a yacht is linked, the berth recommender
   *  reads the yacht's dimensions instead of the desired_* columns
   *  above. Per migration 0087. Defaults false everywhere it isn't
   *  explicitly set. */
  useYachtDimensions: z.boolean().optional(),
});

// ─── Update ──────────────────────────────────────────────────────────────────

// C-03: pipelineStage MUST flow through changeInterestStage / the /stage
// endpoint, which enforces canTransitionStage + override-permission +
// override-reason. Omitting it from the generic update schema closes the
// bypass surface where a PATCH /interests/[id] could drive an interest to
// any stage with no guards, no audit-as-stage-change, and no override
// reason.
export const updateInterestSchema = createInterestSchema
  .omit({ clientId: true, tagIds: true, pipelineStage: true })
  .partial();

// ─── Change Stage ─────────────────────────────────────────────────────────────

export const changeStageSchema = z.object({
  pipelineStage: z.enum(PIPELINE_STAGES),
  reason: z.string().optional(),
  /** Bypass the canTransitionStage transition table. Requires the caller
   *  to hold the `interests.override_stage` permission. Reason becomes
   *  required when override=true (recorded in the audit log). */
  override: z.boolean().optional(),
  /** Optional ISO date (YYYY-MM-DD or full ISO timestamp) to stamp on the
   *  matching milestone column instead of "now". Used when a rep marks a
   *  milestone manually (e.g. deposit received yesterday) so the recorded
   *  date reflects the real event instead of the click time. */
  milestoneDate: z
    .string()
    .regex(/^\d{4}-\d{2}-\d{2}(T.*)?$/)
    .optional(),
});

// ─── Outcome (Won / Lost) ─────────────────────────────────────────────────────

export const INTEREST_OUTCOMES = [
  'won',
  'lost_other_marina',
  'lost_unqualified',
  'lost_no_response',
  'lost_other',
  'cancelled',
] as const;

export type InterestOutcome = (typeof INTEREST_OUTCOMES)[number];

export const setOutcomeSchema = z.object({
  outcome: z.enum(INTEREST_OUTCOMES),
  reason: z.string().max(2000).optional(),
});

export const clearOutcomeSchema = z.object({
  // Stage to revert to when reopening. When omitted the service picks the
  // stage immediately before the outcome was set; falls back to qualified.
  reopenStage: z.enum(PIPELINE_STAGES).optional(),
});

// ─── List ─────────────────────────────────────────────────────────────────────

export const listInterestsSchema = baseListQuerySchema.extend({
  clientId: z.string().optional(),
  yachtId: z.string().optional(),
  berthId: z.string().optional(),
  pipelineStage: z
    .string()
    .transform((v) => v.split(',').filter(Boolean))
    .optional(),
  leadCategory: z.enum(LEAD_CATEGORIES).optional(),
  eoiStatus: z.string().optional(),
  tagIds: z
    .string()
    .transform((v) => v.split(',').filter(Boolean))
    .optional(),
});

// ─── Board (kanban) ───────────────────────────────────────────────────────────

/**
 * Filters accepted by GET /api/v1/interests/board. Strict subset of
 * listInterestsSchema - `pipelineStage` and `includeArchived` are
 * intentionally omitted (the columns ARE the stages, archived deals
 * never belong on the board). No pagination params either.
 */
export const boardFiltersSchema = z.object({
  search: z.string().optional(),
  leadCategory: z.enum(LEAD_CATEGORIES).optional(),
  source: z.string().optional(),
  eoiStatus: z.string().optional(),
  tagIds: z
    .string()
    .transform((v) => v.split(',').filter(Boolean))
    .optional(),
});

export type BoardFiltersInput = z.infer<typeof boardFiltersSchema>;

// ─── Waiting List ─────────────────────────────────────────────────────────────

export const waitingListAddSchema = z.object({
  clientId: z.string().min(1),
  priority: z.enum(['normal', 'high']).default('normal'),
  notifyPref: z.enum(['email', 'in_app', 'both']).default('email'),
  notes: z.string().optional(),
});

// ─── Generate Recommendations ─────────────────────────────────────────────────

export const generateRecommendationsSchema = z.object({
  interestId: z.string().min(1),
});

// ─── Public Interest ──────────────────────────────────────────────────────────

const addressSchema = z.object({
  street: z.string().max(500).optional(),
  city: z.string().max(200).optional(),
  /** ISO 3166-2 subdivision code (e.g. 'PL-MZ'). */
  subdivisionIso: optionalSubdivisionIsoSchema.optional(),
  postalCode: z.string().max(50).optional(),
  /** ISO-3166-1 alpha-2 country code. */
  countryIso: optionalCountryIsoSchema.optional(),
});

// Nested yacht block. Public submissions must now include yacht data because the
// route inserts a yacht row as part of the trio (client + yacht + interest).
const publicYachtSchema = z.object({
  name: z.string().min(1).max(200),
  hullNumber: z.string().max(100).optional(),
  registration: z.string().max(100).optional(),
  flag: z.string().max(100).optional(),
  yearBuilt: z.coerce.number().int().min(1800).max(2100).optional(),
  lengthFt: z.coerce.number().positive().optional(),
  widthFt: z.coerce.number().positive().optional(),
  draftFt: z.coerce.number().positive().optional(),
});

// Optional company block. If provided, the route upserts a company row (match
// case-insensitively by (portId, name)) and adds an active membership linking
// the submitting client to the company with the chosen role.
const publicCompanySchema = z.object({
  name: z.string().min(1).max(200),
  legalName: z.string().max(200).optional(),
  taxId: z.string().max(100).optional(),
  /** ISO-3166-1 alpha-2 country of incorporation. */
  incorporationCountryIso: optionalCountryIsoSchema.optional(),
  /** ISO 3166-2 state/province of incorporation. */
  incorporationSubdivisionIso: optionalSubdivisionIsoSchema.optional(),
  role: z
    .enum([
      'director',
      'officer',
      'broker',
      'representative',
      'legal_counsel',
      'employee',
      'shareholder',
      'other',
    ])
    .optional()
    .default('representative'),
});

export const publicInterestSchema = z
  .object({
    // New: first/last split
    firstName: z.string().min(1).max(100).optional(),
    lastName: z.string().min(1).max(100).optional(),
    // Backward compat
    fullName: z.string().min(1).max(200).optional(),
    email: z.string().email(),
    phone: z.string().min(1),
    /** Pre-normalized E.164 form, optional for backwards compat. */
    phoneE164: optionalPhoneE164Schema.optional(),
    /** ISO-3166-1 alpha-2 country the phone was parsed against. */
    phoneCountry: optionalCountryIsoSchema.optional(),
    /** ISO-3166-1 alpha-2 nationality. */
    nationalityIso: optionalCountryIsoSchema.optional(),
    preferredContactMethod: z.enum(['email', 'phone', 'sms']).optional(),
    mooringNumber: z.string().max(50).optional(),
    // NEW: required structured yacht block. Public submissions after the
    // data-model refactor MUST include yacht data.
    yacht: publicYachtSchema,
    // NEW: optional company block - creates/upserts a company and adds a
    // membership linking the submitting client to it.
    company: publicCompanySchema.optional(),
    source: z.literal('website').default('website'),
    address: addressSchema.optional(),
  })
  .refine((data) => data.fullName || (data.firstName && data.lastName), {
    message: 'Either fullName or both firstName and lastName are required',
    path: ['fullName'],
  });

// ─── Reorder Waiting List ─────────────────────────────────────────────────────

export const reorderWaitingListSchema = z.object({
  entryId: z.string().min(1),
  newPosition: z.coerce.number().int().min(1),
});

// ─── Types ────────────────────────────────────────────────────────────────────

export type CreateInterestInput = z.infer<typeof createInterestSchema>;
export type UpdateInterestInput = z.infer<typeof updateInterestSchema>;
export type ChangeStageInput = z.infer<typeof changeStageSchema>;
export type ListInterestsInput = z.infer<typeof listInterestsSchema>;
export type WaitingListAddInput = z.infer<typeof waitingListAddSchema>;
export type PublicInterestInput = z.infer<typeof publicInterestSchema>;
export type ReorderWaitingListInput = z.infer<typeof reorderWaitingListSchema>;
export type SetOutcomeInput = z.infer<typeof setOutcomeSchema>;
export type ClearOutcomeInput = z.infer<typeof clearOutcomeSchema>;
