import { describe, it, expect } from 'vitest';

import { buildDocumensoPayload } from '@/lib/services/documenso-payload';
import type { EoiContext } from '@/lib/services/eoi-context';

function makeContext(overrides?: Partial<EoiContext>): EoiContext {
  return {
    client: {
      id: 'client-fixture-1',
      fullName: 'Alice Smith',
      nationality: 'US',
      primaryEmail: 'alice@example.com',
      primaryPhone: '+1-555-0100',
      address: {
        street: '123 Main St',
        city: 'Austin',
        subdivision: 'TX',
        postalCode: '78701',
        country: 'United States',
        countryIso: 'US',
      },
    },
    yacht: {
      id: 'yacht-fixture-1',
      name: 'Sea Breeze',
      lengthFt: '45',
      widthFt: '14',
      draftFt: '6',
      lengthM: null,
      widthM: null,
      draftM: null,
      lengthUnit: 'ft' as const,
      widthUnit: 'ft' as const,
      draftUnit: 'ft' as const,
      hullNumber: 'ABC-123',
      flag: 'US',
      yearBuilt: 2020,
    },
    company: null,
    owner: { type: 'client', name: 'Alice Smith' },
    berth: {
      mooringNumber: 'A12',
      area: 'North Dock',
      lengthFt: '50',
      price: '1200',
      priceCurrency: 'USD',
      tenureType: 'permanent',
    },
    eoiBerthRange: 'A12',
    interest: {
      stage: 'open',
      leadCategory: null,
      dateFirstContact: null,
      notes: null,
    },
    port: {
      name: 'Port Nimara',
      defaultCurrency: 'USD',
    },
    date: { today: '2026-04-23', year: '2026' },
    ...overrides,
  };
}

const OPTIONS = {
  interestId: 'int-123',
  clientRecipientId: 192,
  developerRecipientId: 193,
  approvalRecipientId: 194,
};

describe('buildDocumensoPayload', () => {
  it('builds title as "{fullName}-EOI-NDA-{berthRange|mooringNumber}"', () => {
    const payload = buildDocumensoPayload(makeContext(), OPTIONS);
    // Fixture has primary mooring A12, so the title suffix is "-A12".
    expect(payload.title).toBe('Alice Smith-EOI-NDA-A12');
  });

  it('omits berth suffix from title when no berth is linked', () => {
    const ctx = makeContext({ berth: null, eoiBerthRange: '' });
    const payload = buildDocumensoPayload(ctx, OPTIONS);
    expect(payload.title).toBe('Alice Smith-EOI-NDA');
  });

  it('builds externalId as "loi-{interestId}"', () => {
    const payload = buildDocumensoPayload(makeContext(), OPTIONS);
    expect(payload.externalId).toBe('loi-int-123');
  });

  it('formats formValues with all EoiContext fields', () => {
    const payload = buildDocumensoPayload(makeContext(), OPTIONS);
    expect(payload.formValues).toEqual({
      Name: 'Alice Smith',
      Email: 'alice@example.com',
      Address: '123 Main St, Austin, TX, 78701, US',
      'Yacht Name': 'Sea Breeze',
      Length: '45 ft',
      Width: '14 ft',
      Draft: '6 ft',
      // Berth Number carries the formatBerthRange output - single-
      // berth EOI duplicates the primary mooring; multi-berth shows
      // the compact range. The separate 'Berth Range' formValue key
      // was retired 2026-05-14 (the Documenso template never had
      // that field, so the value was silently dropped).
      'Berth Number': 'A12',
      Lease_10: false,
      Purchase: true,
    });
  });

  it('renders Berth Number as the multi-berth range string when bundle has > 1', () => {
    const ctx = makeContext({ eoiBerthRange: 'A1-A3, B5' });
    const payload = buildDocumensoPayload(ctx, OPTIONS);
    expect(payload.formValues['Berth Number']).toBe('A1-A3, B5');
  });

  it('defaults missing primaryEmail to empty string', () => {
    const ctx = makeContext({ client: { ...makeContext().client, primaryEmail: null } });
    const payload = buildDocumensoPayload(ctx, OPTIONS);
    expect(payload.formValues.Email).toBe('');
    expect(payload.recipients[0]!.email).toBe('');
  });

  it('defaults missing yacht dimensions to empty strings', () => {
    const baseYacht = makeContext().yacht!;
    const ctx = makeContext({
      yacht: { ...baseYacht, lengthFt: null, widthFt: null, draftFt: null },
    });
    const payload = buildDocumensoPayload(ctx, OPTIONS);
    expect(payload.formValues.Length).toBe('');
    expect(payload.formValues.Width).toBe('');
    expect(payload.formValues.Draft).toBe('');
  });

  it('renders empty Section 3 when yacht and berth are not linked', () => {
    // Also explicitly clear the berth-range fallback that defaults to
    // the primary mooring - when there's no berth AND no bundle, the
    // form field renders as empty.
    const ctx = makeContext({ yacht: null, berth: null, eoiBerthRange: '' });
    const payload = buildDocumensoPayload(ctx, OPTIONS);
    expect(payload.formValues['Yacht Name']).toBe('');
    expect(payload.formValues.Length).toBe('');
    expect(payload.formValues.Width).toBe('');
    expect(payload.formValues.Draft).toBe('');
    expect(payload.formValues['Berth Number']).toBe('');
  });

  it('formats empty address when client has no address', () => {
    const ctx = makeContext({ client: { ...makeContext().client, address: null } });
    const payload = buildDocumensoPayload(ctx, OPTIONS);
    expect(payload.formValues.Address).toBe('');
  });

  it('skips null parts in address', () => {
    const ctx = makeContext({
      client: {
        ...makeContext().client,
        address: {
          street: '',
          city: 'Austin',
          subdivision: '',
          postalCode: '',
          country: 'United States',
          countryIso: 'US',
        },
      },
    });
    const payload = buildDocumensoPayload(ctx, OPTIONS);
    expect(payload.formValues.Address).toBe('Austin, US');
  });

  it('sets Lease_10=false and Purchase=true (hardcoded)', () => {
    const payload = buildDocumensoPayload(makeContext(), OPTIONS);
    expect(payload.formValues.Lease_10).toBe(false);
    expect(payload.formValues.Purchase).toBe(true);
  });

  it('includes client, developer, and approver recipients in signing order', () => {
    const payload = buildDocumensoPayload(makeContext(), OPTIONS);
    expect(payload.recipients).toHaveLength(3);
    expect(payload.recipients[0]).toEqual({
      id: 192,
      name: 'Alice Smith',
      email: 'alice@example.com',
      role: 'SIGNER',
      signingOrder: 1,
    });
    // Developer + approver name/email default to '' so Documenso falls
    // through to the template-stored values for those signers (we only
    // override when the admin explicitly sets them via OPTIONS).
    expect(payload.recipients[1]).toEqual({
      id: 193,
      name: '',
      email: '',
      role: 'SIGNER',
      signingOrder: 2,
    });
    expect(payload.recipients[2]).toEqual({
      id: 194,
      name: '',
      email: '',
      role: 'APPROVER',
      signingOrder: 3,
    });
  });

  it('allows overriding developer/approver recipient names', () => {
    const payload = buildDocumensoPayload(makeContext(), {
      ...OPTIONS,
      developerName: 'Custom Dev',
      developerEmail: 'dev@custom.com',
      approverName: 'Custom Approver',
      approverEmail: 'approve@custom.com',
    });
    expect(payload.recipients[1]!.name).toBe('Custom Dev');
    expect(payload.recipients[1]!.email).toBe('dev@custom.com');
    expect(payload.recipients[2]!.name).toBe('Custom Approver');
    expect(payload.recipients[2]!.email).toBe('approve@custom.com');
  });

  it('builds message with port name and greeting', () => {
    const payload = buildDocumensoPayload(makeContext(), OPTIONS);
    expect(payload.meta.message).toContain('Dear Alice Smith');
    expect(payload.meta.message).toContain('Port Nimara');
    expect(payload.meta.message).toContain('Best Regards');
    // No company on-behalf block for client-owned yachts
    expect(payload.meta.message).not.toContain('On behalf of');
  });

  it('adds company on-behalf block for company-owned yachts', () => {
    const ctx = makeContext({
      company: {
        name: 'Aegean Holdings',
        legalName: 'Aegean Holdings SA',
        taxId: null,
        billingAddress: null,
      },
      owner: { type: 'company', name: 'Aegean Holdings', legalName: 'Aegean Holdings SA' },
    });
    const payload = buildDocumensoPayload(ctx, OPTIONS);
    expect(payload.meta.message).toContain('On behalf of Aegean Holdings SA');
  });

  it('uses company name when legalName is missing in on-behalf block', () => {
    const ctx = makeContext({
      company: { name: 'Blue Seas', legalName: null, taxId: null, billingAddress: null },
      owner: { type: 'company', name: 'Blue Seas' },
    });
    const payload = buildDocumensoPayload(ctx, OPTIONS);
    expect(payload.meta.message).toContain('On behalf of Blue Seas');
  });

  it('uses empty default redirect URL when not provided (Documenso falls back to its own page)', () => {
    // Multi-tenant: never hardcode a single port's marketing-site URL
    // here. When the admin hasn't configured a redirect, send empty
    // string so Documenso uses its built-in post-sign page. Per-port
    // override flows through getPortDocumensoConfig → redirectUrl.
    const payload = buildDocumensoPayload(makeContext(), OPTIONS);
    expect(payload.meta.redirectUrl).toBe('');
  });

  it('uses custom redirect URL when provided', () => {
    const payload = buildDocumensoPayload(makeContext(), {
      ...OPTIONS,
      redirectUrl: 'https://custom.example.com',
    });
    expect(payload.meta.redirectUrl).toBe('https://custom.example.com');
  });
});
