import { and, eq } from 'drizzle-orm';

import { db } from '@/lib/db';
import { systemSettings } from '@/lib/db/schema/system';
import { user, userProfiles } from '@/lib/db/schema/users';
import type { EoiContext } from '@/lib/services/eoi-context';
import { readSetting, SETTING_KEYS } from '@/lib/services/port-config';

export interface DocumensoTemplatePayload {
  title: string;
  externalId: string;
  meta: {
    message: string;
    subject: string;
    redirectUrl: string;
    distributionMethod: 'NONE' | 'EMAIL';
    /**
     * PARALLEL = all signers can sign in any order (default, current behaviour).
     * SEQUENTIAL = signers must complete in the order their `signingOrder`
     * number dictates (client → developer → approver for EOI). v2 enforces
     * this server-side; v1 ignores the key and behaves as PARALLEL regardless.
     */
    signingOrder?: 'PARALLEL' | 'SEQUENTIAL';
  };
  /**
   * Legacy v1 path: form-field values keyed by field NAME. Documenso v1.13.x
   * accepts only this shape. v2 instances accept it via backward compat too.
   */
  formValues: {
    Name: string;
    Email: string;
    Address: string;
    'Yacht Name': string;
    Length: string;
    Width: string;
    Draft: string;
    /**
     * Berth mooring as the human sees it. Single-berth EOI → the
     * primary mooring (e.g. "A1"). Multi-berth EOI → the compact range
     * (e.g. "A1-A3, B5") produced by `formatBerthRange()`. Single-
     * berth output is byte-identical to the legacy primary-only path.
     * 2026-05-14: collapsed the prior separate `Berth Range` form field
     * into this one - the Documenso template has only `Berth Number`,
     * and Documenso silently dropped unknown formValues.
     */
    'Berth Number': string;
    Lease_10: boolean;
    Purchase: boolean;
  };
  /**
   * v2-native path: prefill values keyed by field ID. Generated by mapping
   * each `formValues` entry through the cached `documenso_eoi_field_map`
   * (name → ID) discovered via the admin's "Sync from Documenso" button.
   * v1 instances ignore this field; v2 instances accept either prefillFields
   * OR formValues but prefillFields-by-ID is the canonical modern path.
   */
  prefillFields?: Array<{
    id: number;
    type: 'text' | 'number' | 'date' | 'checkbox' | 'dropdown';
    value: string;
  }>;
  recipients: Array<{
    id: number;
    name: string;
    email: string;
    role: 'SIGNER' | 'APPROVER' | 'CC' | 'VIEWER';
    signingOrder: number;
  }>;
  /**
   * Extra recipients beyond the canonical client + developer + approver trio.
   * Used by the "send a copy to my manager" workflow: pass CC slots here and
   * they'll be appended to the recipients array at send time.
   */
  extraRecipients?: Array<{
    id: number;
    name: string;
    email: string;
    role: 'CC' | 'VIEWER';
    signingOrder?: number;
  }>;
}

export interface DocumensoPayloadOptions {
  /** `interestId` used to build `externalId` and Documenso referencing. */
  interestId: string;
  /** Documenso recipient IDs - come from env vars. */
  clientRecipientId: number;
  developerRecipientId: number;
  approvalRecipientId: number;
  /** Hardcoded developer + approver names/emails (legacy). */
  developerName?: string;
  developerEmail?: string;
  approverName?: string;
  approverEmail?: string;
  /** Redirect URL after signing. Defaults to the app URL. */
  redirectUrl?: string;
  /**
   * PARALLEL (default) or SEQUENTIAL - v2-only enforcement (v1 ignores).
   * Set via per-port `documenso_signing_order` system_settings key.
   */
  signingOrder?: 'PARALLEL' | 'SEQUENTIAL';
  /**
   * Optional extra recipients beyond the canonical client+developer+approver
   * trio. Used by the "send a copy to my manager" workflow. CC = receives a
   * copy of the signed PDF; VIEWER = can view but not sign. Slot IDs must
   * exist on the Documenso template (CRM operator adds them in the template
   * editor first). v2-only on v2 instances; v1 ignores unknown roles.
   */
  extraRecipients?: Array<{
    id: number;
    name: string;
    email: string;
    role: 'CC' | 'VIEWER';
    signingOrder?: number;
  }>;
  /**
   * Which side of the yacht's stored dimensions (ft|m) flows into the EOI's
   * Length/Width/Draft formValues. Defaults to 'ft' when omitted for legacy
   * call sites; the EOI-generate drawer always supplies the rep's choice.
   */
  dimensionUnit?: 'ft' | 'm';
}

// Empty string lets Documenso fall back to its own default post-sign
// landing page when the port admin hasn't configured a redirect URL.
// Never hardcode a tenant's marketing-site URL here - that would route
// every other port's signers to the wrong host.
const DEFAULT_REDIRECT_URL = '';

export interface EoiSignerConfig {
  developer: { name: string; email: string };
  approver: { name: string; email: string };
}

const EMPTY_SIGNERS: EoiSignerConfig = {
  developer: { name: '', email: '' },
  approver: { name: '', email: '' },
};

function isSignerEntry(v: unknown): v is { name: string; email: string } {
  return (
    !!v &&
    typeof v === 'object' &&
    typeof (v as Record<string, unknown>).name === 'string' &&
    typeof (v as Record<string, unknown>).email === 'string' &&
    !!(v as Record<string, string>).name &&
    !!(v as Record<string, string>).email
  );
}

/** Look up `{name, email}` for a CRM user id by joining `userProfiles`
 *  (display name + signing override) + `user` (auth/login email). The signing
 *  email is `userProfiles.signingEmail` when set, otherwise the login
 *  `user.email` — so a user who logs in as `abbie@` can sign on behalf of a
 *  shared role mailbox (`sales@`) without changing their login identity.
 *  Returns nulls on miss. */
async function resolveCrmUser(
  userId: string | null,
): Promise<{ name: string; email: string } | null> {
  if (!userId) return null;
  const [row] = await db
    .select({
      displayName: userProfiles.displayName,
      loginEmail: user.email,
      signingEmail: userProfiles.signingEmail,
    })
    .from(user)
    .leftJoin(userProfiles, eq(userProfiles.userId, user.id))
    .where(eq(user.id, userId))
    .limit(1);
  if (!row) return null;
  const email = row.signingEmail ?? row.loginEmail;
  if (!email) return null;
  return { name: row.displayName ?? email, email };
}

/**
 * Resolve the developer + approver name/email for the EOI signing trio.
 *
 * Priority chain per slot (highest → lowest):
 *   1. Linked CRM user (`documenso_<role>_user_id`) - recommended path
 *      because "the person on this slot" changes via a CRM admin re-link,
 *      not a Documenso template edit. The display name comes from
 *      `userProfiles.displayName`, the email from `user.email`.
 *   2. Free-text overrides (`documenso_<role>_name` +
 *      `documenso_<role>_email`) - for ports where the signer isn't a
 *      CRM-platform user (e.g. external counsel).
 *   3. Legacy `eoi_signers` JSON blob - kept for backward compat with
 *      ports that haven't migrated to the registry-driven settings yet.
 *   4. Empty strings - let the Documenso template's stored values win.
 *
 * Either slot can resolve via a different tier than the other.
 */
export async function getPortEoiSigners(portId: string): Promise<EoiSignerConfig> {
  const [developerUserId, approverUserId, devName, devEmail, apprName, apprEmail, legacyRow] =
    await Promise.all([
      readSetting<string>(SETTING_KEYS.documensoDeveloperUserId, portId),
      readSetting<string>(SETTING_KEYS.documensoApproverUserId, portId),
      readSetting<string>(SETTING_KEYS.documensoDeveloperName, portId),
      readSetting<string>(SETTING_KEYS.documensoDeveloperEmail, portId),
      readSetting<string>(SETTING_KEYS.documensoApproverName, portId),
      readSetting<string>(SETTING_KEYS.documensoApproverEmail, portId),
      db.query.systemSettings.findFirst({
        where: and(eq(systemSettings.key, 'eoi_signers'), eq(systemSettings.portId, portId)),
      }),
    ]);

  const legacyValue = legacyRow?.value as Record<string, unknown> | undefined;
  const legacyDev =
    legacyValue && isSignerEntry(legacyValue.developer) ? legacyValue.developer : null;
  const legacyApr =
    legacyValue && isSignerEntry(legacyValue.approver) ? legacyValue.approver : null;

  const [developerFromUser, approverFromUser] = await Promise.all([
    resolveCrmUser(developerUserId ?? null),
    resolveCrmUser(approverUserId ?? null),
  ]);

  const developer =
    developerFromUser ??
    (devName && devEmail ? { name: devName, email: devEmail } : null) ??
    legacyDev ??
    EMPTY_SIGNERS.developer;

  const approver =
    approverFromUser ??
    (apprName && apprEmail ? { name: apprName, email: apprEmail } : null) ??
    legacyApr ??
    EMPTY_SIGNERS.approver;

  return { developer, approver };
}

function formatAddress(address: EoiContext['client']['address']): string {
  if (!address) return '';
  // Shortest comprehensive format so the line fits the EOI's Address field:
  // street, city, REGION (ISO-3166-2 suffix), postal, COUNTRY (alpha-2).
  return [address.street, address.city, address.subdivision, address.postalCode, address.countryIso]
    .filter(Boolean)
    .join(', ');
}

function buildMessage(context: EoiContext): string {
  const greeting = `Dear ${context.client.fullName},`;
  const body = `Thank you for your interest in a berth at ${context.port.name}. Please click the link above to sign your LOI.`;
  const onBehalf =
    context.owner.type === 'company' && context.company
      ? `\n\nOn behalf of ${context.company.legalName ?? context.company.name} (representing the yacht's owner).`
      : '';
  const footer = `\n\nBest Regards,\n${context.port.name} Team`;
  return `${greeting}\n\n${body}${onBehalf}${footer}`;
}

export function buildDocumensoPayload(
  context: EoiContext,
  options: DocumensoPayloadOptions,
  /**
   * Cached field name → ID map from the per-port `documenso_eoi_field_map`
   * setting (populated by the admin "Sync from Documenso" button). When
   * provided, the payload also emits `prefillFields` keyed by ID - required
   * by v2's /template/use. v1 instances ignore this field; v2 instances
   * accept either prefillFields OR the legacy formValues shape.
   */
  fieldMap?: Record<string, number> | null,
): DocumensoTemplatePayload {
  // Honour the rep's unit choice from the EOI drawer's toggle. Defaults to
  // 'ft' for legacy call sites that don't pass `dimensionUnit`; new code
  // paths (generateAndSign + the drawer) always set it explicitly.
  // Append the unit suffix to every dimension value so the rendered EOI
  // reads "45 ft" / "13.7 m" rather than the bare number - the original
  // form field doesn't tell signers which unit they're looking at.
  const dimUnit: 'ft' | 'm' = options.dimensionUnit ?? 'ft';
  const yachtLength = dimUnit === 'ft' ? context.yacht?.lengthFt : context.yacht?.lengthM;
  const yachtWidth = dimUnit === 'ft' ? context.yacht?.widthFt : context.yacht?.widthM;
  const yachtDraft = dimUnit === 'ft' ? context.yacht?.draftFt : context.yacht?.draftM;
  const withUnit = (v: string | null | undefined): string =>
    v && String(v).trim() ? `${String(v).trim()} ${dimUnit}` : '';

  const formValues = {
    Name: context.client.fullName,
    Email: context.client.primaryEmail ?? '',
    Address: formatAddress(context.client.address),
    // Yacht + berth are optional EOI fields; when not linked, render as
    // empty strings so the corresponding template inputs stay blank.
    'Yacht Name': context.yacht?.name ?? '',
    Length: withUnit(yachtLength),
    Width: withUnit(yachtWidth),
    Draft: withUnit(yachtDraft),
    // formatBerthRange(['A1']) === 'A1' - so single-berth EOIs render
    // identically to the legacy primary-only flow; multi-berth EOIs
    // now actually show the full range instead of just the primary
    // mooring.
    'Berth Number': context.eoiBerthRange || (context.berth?.mooringNumber ?? ''),
    Lease_10: false,
    Purchase: true,
  } as const;

  // v2's prefillFields-by-ID emission. Map every formValue entry through the
  // cached field map; skip entries that aren't in the map (template doesn't
  // have that field, which is fine - Documenso silently drops unknown ones
  // in v1 too).
  const prefillFields = fieldMap
    ? Object.entries(formValues)
        .map(([label, value]) => {
          const fieldId = fieldMap[label];
          if (fieldId == null) return null;
          const isBoolean = typeof value === 'boolean';
          return {
            id: fieldId,
            type: isBoolean ? ('checkbox' as const) : ('text' as const),
            value: String(value),
          };
        })
        .filter((x): x is { id: number; type: 'text' | 'checkbox'; value: string } => x !== null)
    : undefined;

  // Title format: "<full name>-EOI-NDA[-<berth range>]". When the EOI is
  // tied to one or more berths, append the formatted range so the doc
  // identifies the deal at a glance in lists and Documenso dashboards.
  const berthSuffix = context.eoiBerthRange || context.berth?.mooringNumber || '';
  return {
    title: berthSuffix
      ? `${context.client.fullName}-EOI-NDA-${berthSuffix}`
      : `${context.client.fullName}-EOI-NDA`,
    externalId: `loi-${options.interestId}`,
    meta: {
      message: buildMessage(context),
      subject: 'Your LOI is ready to be signed',
      redirectUrl: options.redirectUrl ?? DEFAULT_REDIRECT_URL,
      distributionMethod: 'NONE',
      ...(options.signingOrder ? { signingOrder: options.signingOrder } : {}),
    },
    formValues,
    ...(prefillFields && prefillFields.length > 0 ? { prefillFields } : {}),
    // Per Documenso v2's /template/use schema, `email` and `name` accept "" as
    // a sentinel meaning "use the value baked into the template recipient".
    // So when an admin leaves the developer/approver name/email blank in our
    // admin settings, we pass "" rather than a hardcoded fallback - Documenso
    // then takes the email/name set on the template itself. A non-empty
    // admin value still wins (overrides the template at send time).
    recipients: [
      {
        id: options.clientRecipientId,
        name: context.client.fullName,
        email: context.client.primaryEmail ?? '',
        role: 'SIGNER',
        signingOrder: 1,
      },
      {
        id: options.developerRecipientId,
        name: options.developerName ?? '',
        email: options.developerEmail ?? '',
        role: 'SIGNER',
        signingOrder: 2,
      },
      {
        id: options.approvalRecipientId,
        name: options.approverName ?? '',
        email: options.approverEmail ?? '',
        role: 'APPROVER',
        signingOrder: 3,
      },
      // Append CC / VIEWER slots after the canonical trio so their signing
      // order doesn't collide with 1/2/3. Documenso doesn't require
      // signingOrder uniqueness across non-signing roles but we still hand
      // out monotonic numbers (4, 5, …) for predictability.
      ...(options.extraRecipients ?? []).map((extra, idx) => ({
        id: extra.id,
        name: extra.name,
        email: extra.email,
        role: extra.role,
        signingOrder: extra.signingOrder ?? 4 + idx,
      })),
    ],
  };
}
