import { describe, expect, it } from 'vitest'
import { attachmentFileName, axleSummary, dim, dimensionLine, fitAttachments, payerLabel, permitRequestData, previousPermitSummary, vehicleLine } from '@/lib/domain/permit-request-email'
import { DEFAULT_TEMPLATES, renderTemplateClean } from '@/lib/email-templates'
import type { Permit, Trip, TripUnit } from '@/types/db'

/** The permit request email to Synchron Permits (Nash, 2026-09-23). */
const trip = { id: 't1', ref_code: 'HH-70305660', carrier_name: 'XYZ Trucking', unit_number: 'T-114', origin: 'Charleston, SC', destination: 'Schertz, TX', commodity: 'Prefab section', load_length_in: 600, load_width_in: 150, load_height_in: 162, load_weight_lbs: 48000, overall_length_in: 936, overall_width_in: 150, overall_height_in: 182, overall_weight_lbs: 92000, pickup_date: '2026-09-24', delivery_date: null, source_order_number: '70305660' } as unknown as Trip
const unit = { axle_count: 7, axle_spacings_in: [186, 54, 432], kingpin_to_rear_axle_in: 516, axle_weights_lbs: [12000, 17000], truck_unit_number: 'T-114', truck_vin: 'VIN1', truck_make: 'Peterbilt', truck_model: '389', truck_year: 2022, trailer_unit_number: null, trailer_vin: null, trailer_make: 'Trail King', trailer_model: null, trailer_year: null, trailer_axle_count: 3 } as unknown as TripUnit
const requester = { name: 'Val Broker', email: 'sam@xyz.com', phone: '(555) 010-2030', role: 'dispatcher', company: 'XYZ Trucking', companyMc: '1234567' }

describe('formatting', () => {
  it('dimensions read as feet-inches with inches in brackets', () => {
    expect(dim(600)).toBe(`50' (600 in)`)
    expect(dim(162)).toBe(`13'6" (162 in)`)
    expect(dim(null)).toBe('not on file')
  })
  it('axles, truck and trailer lines', () => {
    expect(axleSummary(unit)).toBe(`7 axles · spacings 15'6" · 4'6" · 36' · KPTRA 43' · axle weights 12,000 / 17,000 lbs`)
    expect(axleSummary(null)).toBe('Unit sheet not on file yet')
    expect(vehicleLine('truck', unit)).toBe('2022 Peterbilt 389 · unit T-114 · VIN VIN1')
    expect(vehicleLine('trailer', unit)).toBe('Trail King · 3 axles')
  })
  it('who pays', () => {
    expect(payerLabel('requester', requester, trip)).toBe('The requester — Val Broker, XYZ Trucking')
    expect(payerLabel('carrier', requester, trip)).toBe('The carrier (XYZ Trucking)')
    expect(payerLabel('broker', { ...requester, role: 'broker', company: 'ABC Brokerage' }, trip)).toBe('The freight broker on this trip (Val Broker, ABC Brokerage)')
  })
  it('previous permit or first permit', () => {
    const p = { permit_number: '48843549-GA', effective_date: '2026-08-04', expiration_date: '2026-09-03', permit_length_in: 600, permit_width_in: 150, permit_height_in: 162, permit_weight_lbs: 92000 } as unknown as Permit
    expect(previousPermitSummary(p, 'Georgia')).toContain('permit 48843549-GA')
    expect(previousPermitSummary(p, 'Georgia')).toContain('expired')
    expect(previousPermitSummary(p, 'Georgia')).toContain('A copy is attached')
    expect(previousPermitSummary(null, 'Tennessee')).toBe('No Tennessee permit is on file for this order yet — this is a first permit for Tennessee.')
  })
})

describe('the email', () => {
  it('fills every section and renders without leftovers', () => {
    const data = permitRequestData({ trip, unit, stateCode: 'tn', previousPermit: null, requester, payer: 'requester', notes: 'Please rush.', orderNumber: 'SP-1', attachments: [{ name: 'rc.pdf', label: 'Rate confirmation', sizeBytes: 200_000 }], workspaceLink: 'https://x/trips/t1', synchronEmail: 'info@synchronpermits.com', now: new Date('2026-09-23T15:00:00Z') })
    expect(data.permit_state).toBe('Tennessee')
    expect(data.permit_state_code).toBe('TN')
    expect(data.load_dimensions).toBe(`50' (600 in) long · 12'6" (150 in) wide · 13'6" (162 in) high · 48,000 lbs`)
    expect(data.overall_dimensions).toContain('92,000 lbs')
    expect(data.requester_company).toBe('XYZ Trucking (MC 1234567)')
    expect(data.rate_confirmation_summary).toContain('rc.pdf')
    expect(data.attachments_list).toBe('- Rate confirmation: rc.pdf (195 KB)')
    expect(data.requester_line).toBe('Val Broker (Carrier Dispatcher, XYZ Trucking · MC 1234567)')
    expect(data.delivery_date).toBe('')
    const t = DEFAULT_TEMPLATES.find((x) => x.key === 'permit_reorder_request')!
    const body = renderTemplateClean(t.body, { ...data, support_email: 'support@x' })
    expect(body).not.toMatch(/\{\{/)
    expect(body).toContain('Val Broker (Carrier Dispatcher, XYZ Trucking · MC 1234567) has requested a NEW Tennessee permit for order HH-70305660')
    expect(body).not.toContain('Delivery date:') // blank lines are dropped, never printed empty
    expect(renderTemplateClean(t.subject, data)).toBe('New Tennessee permit request — order HH-70305660 · XYZ Trucking')
  })
  it('keeps the email under the provider limit, dropping the largest optional file first', () => {
    const files = [{ name: 'rc.pdf', label: 'Rate confirmation', sizeBytes: 7_000_000 }, { name: 'ga.pdf', label: 'Previous GA permit', sizeBytes: 7_500_000 }, { name: 'big.pdf', label: 'Other', sizeBytes: 9_000_000 }]
    const r = fitAttachments(files, 15 * 1024 * 1024)
    expect(r.dropped.map((f) => f.name)).toEqual(['big.pdf'])
    expect(r.kept.map((f) => f.name)).toEqual(['rc.pdf', 'ga.pdf'])
    const tight = fitAttachments(files.slice(0, 2), 8 * 1024 * 1024)
    expect(tight.kept.map((f) => f.name)).toEqual(['ga.pdf']) // the previous permit is the last to go
  })
})

describe('pulled from the actual order, never static (Nash, 2026-09-23)', () => {
  it('the opening sentence survives a requester with no company on file', () => {
    // Regression: renderTemplateClean drops any line holding an empty variable, which
    // silently removed the whole opening sentence when the requester had no company.
    const data = permitRequestData({ trip, unit, stateCode: 'TN', previousPermit: null, requester: { ...requester, company: null, companyMc: null }, payer: null, notes: null, orderNumber: null, attachments: [], workspaceLink: 'https://x/t', synchronEmail: 'synchronpermits@gmail.com' })
    expect(data.requester_line).toBe('Val Broker (Carrier Dispatcher)')
    expect(data.requester_company).toBe('')
    const t = DEFAULT_TEMPLATES.find((x) => x.key === 'permit_reorder_request')!
    const body = renderTemplateClean(t.body, { ...data, support_email: 'support@x' })
    expect(body).toContain('Val Broker (Carrier Dispatcher) has requested a NEW Tennessee permit')
    expect(body).not.toContain('Company:')
  })

  it('only the dimensions actually on the order are printed', () => {
    expect(dimensionLine({ length_in: 290, width_in: 104, height_in: null, weight_lbs: 6880 }, 'none')).toBe(`24'2" (290 in) long · 8'8" (104 in) wide · 6,880 lbs`)
    expect(dimensionLine({ length_in: null, width_in: null, height_in: null, weight_lbs: null }, 'Not on file on this order.')).toBe('Not on file on this order.')
  })

  it('missing overall dimensions fall back to the previous permit for that state, clearly labelled', () => {
    const noOverall = { ...trip, overall_length_in: null, overall_width_in: null, overall_height_in: null, overall_weight_lbs: null } as unknown as Trip
    const prev = { permit_number: '503912', effective_date: null, expiration_date: null, permit_length_in: 1320, permit_width_in: 168, permit_height_in: 180, permit_weight_lbs: null } as unknown as Permit
    const data = permitRequestData({ trip: noOverall, unit, stateCode: 'NV', previousPermit: prev, requester, payer: null, notes: null, orderNumber: null, attachments: [], workspaceLink: 'https://x/t', synchronEmail: 'x@y.com' })
    expect(data.overall_dimensions).toBe(`Not on file on this order. For reference, the previous Nevada permit was issued for 110' (1320 in) long · 14' (168 in) wide · 15' (180 in) high.`)
    const bare = permitRequestData({ trip: noOverall, unit, stateCode: 'NV', previousPermit: null, requester, payer: null, notes: null, orderNumber: null, attachments: [], workspaceLink: 'https://x/t', synchronEmail: 'x@y.com' })
    expect(bare.overall_dimensions).toBe('Not on file on this order — please confirm with the requester.')
  })

  it('attachments are named from the order and the permit, not the storage file name', () => {
    expect(attachmentFileName({ tripRef: 'HH-KX9QG4', label: 'NV permit 503912', originalName: '1789834772_32.pdf' })).toBe('HH-KX9QG4 — NV permit 503912.pdf')
    expect(attachmentFileName({ tripRef: 'HH-KX9QG4', label: 'rate confirmation', originalName: 'RC.PDF' })).toBe('HH-KX9QG4 — rate confirmation.pdf')
    expect(attachmentFileName({ tripRef: 'HH-1', label: 'TN permit A/B', originalName: 'x.png' })).toBe('HH-1 — TN permit A-B.png')
  })
})
