/**
 * Seed script — populates legal-service with realistic GPS Legal test data.
 * Run: npx ts-node src/seed.ts  (from services/legal-service/)
 */

const BASE = 'http://localhost:3200'

async function post(path: string, body: object) {
  const res = await fetch(`${BASE}${path}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
  if (!res.ok) {
    const text = await res.text()
    throw new Error(`POST ${path} failed ${res.status}: ${text}`)
  }
  return res.json()
}

function daysFromNow(n: number): string {
  const d = new Date()
  d.setDate(d.getDate() + n)
  return d.toISOString().split('T')[0]
}

async function main() {
  console.log('Seeding legal-service...')

  // ── Clients ────────────────────────────────────────────────────
  const james = await post('/client-folders', {
    clientType: 'individual',
    firstName: 'James',
    lastName: 'Smith',
    nationality: 'US',
    passportNumber: 'A12345678',
    visaType: 'Non-B',
    visaExpiry: daysFromNow(45),
    email: 'james.smith@email.com',
    phone: '+1-555-0101',
    lineId: 'jsmith_bkk',
    originatingAttorney: 'attorney-001',
    responsibleAttorney: 'attorney-001',
    retainerThreshold: 25000,
    currency: 'THB',
  })
  console.log('Created client:', james.folderNumber, james.displayName)

  const nexus = await post('/client-folders', {
    clientType: 'corporate',
    companyName: 'Nexus Corp Ltd',
    registrationNumber: '0105561234567',
    boiStatus: 'BOI Zone 3 — Manufacturing',
    email: 'legal@nexuscorp.th',
    phone: '+66-2-555-0200',
    originatingAttorney: 'attorney-001',
    responsibleAttorney: 'attorney-001',
    retainerThreshold: 50000,
    currency: 'THB',
  })
  console.log('Created client:', nexus.folderNumber, nexus.displayName)

  const kenji = await post('/client-folders', {
    clientType: 'individual',
    firstName: 'Kenji',
    lastName: 'Tanaka',
    nationality: 'JP',
    passportNumber: 'TK9876543',
    visaType: 'Non-O',
    visaExpiry: daysFromNow(120),
    email: 'kenji.tanaka@jp.com',
    phone: '+81-90-5555-0303',
    originatingAttorney: 'attorney-001',
    responsibleAttorney: 'attorney-001',
    retainerThreshold: 20000,
    currency: 'THB',
  })
  console.log('Created client:', kenji.folderNumber, kenji.displayName)

  const siriwan = await post('/client-folders', {
    clientType: 'individual',
    firstName: 'Siriwan',
    lastName: 'Jaidee',
    nationality: 'TH',
    email: 'siriwan.j@gmail.com',
    phone: '+66-81-555-0404',
    originatingAttorney: 'attorney-001',
    responsibleAttorney: 'attorney-001',
    retainerThreshold: 30000,
    currency: 'THB',
  })
  console.log('Created client:', siriwan.folderNumber, siriwan.displayName)

  const changCorp = await post('/client-folders', {
    clientType: 'corporate',
    companyName: 'Chang Import Co., Ltd.',
    registrationNumber: '0105560001234',
    email: 'admin@changimport.th',
    phone: '+66-2-555-0500',
    originatingAttorney: 'attorney-001',
    responsibleAttorney: 'attorney-001',
    retainerThreshold: 25000,
    currency: 'THB',
  })
  console.log('Created client:', changCorp.folderNumber, changCorp.displayName)

  const jiwoo = await post('/client-folders', {
    clientType: 'individual',
    firstName: 'Ji-woo',
    lastName: 'Kim',
    nationality: 'KR',
    passportNumber: 'M55566677',
    visaType: 'Non-B',
    visaExpiry: daysFromNow(200),
    email: 'jiwoo.kim@work.kr',
    phone: '+82-10-5555-0606',
    originatingAttorney: 'attorney-001',
    responsibleAttorney: 'attorney-001',
    retainerThreshold: 20000,
    currency: 'THB',
  })
  console.log('Created client:', jiwoo.folderNumber, jiwoo.displayName)

  // ── Matters ────────────────────────────────────────────────────
  const mSmith = await post('/matters', {
    clientFolderId: james._id,
    title: 'TM.7 Extension — Smith',
    practiceArea: 'immigration',
    description: 'Non-B visa TM.7 extension application. BOI endorsed.',
    responsibleAttorney: 'attorney-001',
    courtRef: 'TM.7/2026/0041',
    billingType: 'retainer',
    hourlyRate: 5000,
    currency: 'THB',
  })
  console.log('Created matter:', mSmith.matterNumber)

  const mNexus = await post('/matters', {
    clientFolderId: nexus._id,
    title: 'BOI Licence — Nexus Corp',
    practiceArea: 'corporate',
    description: 'BOI Section 12 manufacturing licence for foreign majority ownership.',
    responsibleAttorney: 'attorney-001',
    courtRef: 'BOI/2026/0012',
    billingType: 'fixed',
    fixedFee: 120000,
    currency: 'THB',
  })
  console.log('Created matter:', mNexus.matterNumber)

  const mKenji = await post('/matters', {
    clientFolderId: kenji._id,
    title: 'Retirement Visa — Tanaka',
    practiceArea: 'immigration',
    description: 'Non-O retirement visa conversion and extension.',
    responsibleAttorney: 'attorney-001',
    billingType: 'hourly',
    hourlyRate: 4500,
    currency: 'THB',
  })
  console.log('Created matter:', mKenji.matterNumber)

  const mSiriwan = await post('/matters', {
    clientFolderId: siriwan._id,
    title: 'Chanote Transfer — Jaidee',
    practiceArea: 'property',
    description: 'Transfer of chanote deed, foreign ownership structure via Thai nominee.',
    responsibleAttorney: 'attorney-001',
    billingType: 'fixed',
    fixedFee: 85000,
    currency: 'THB',
  })
  console.log('Created matter:', mSiriwan.matterNumber)

  const mChang = await post('/matters', {
    clientFolderId: changCorp._id,
    title: 'Commercial Dispute — Chang Import',
    practiceArea: 'civil_litigation',
    description: 'Breach of contract claim against supplier.',
    responsibleAttorney: 'attorney-001',
    caseNumber: 'CV-2025-1142',
    judge: 'Somchai Pattanarat',
    billingType: 'hourly',
    hourlyRate: 6000,
    currency: 'THB',
  })
  console.log('Created matter:', mChang.matterNumber)

  const mKim = await post('/matters', {
    clientFolderId: jiwoo._id,
    title: 'Wrongful Termination — Kim',
    practiceArea: 'employment',
    description: 'Unfair dismissal claim against Korean-owned employer.',
    responsibleAttorney: 'attorney-001',
    caseNumber: 'LB-2026-0088',
    billingType: 'hourly',
    hourlyRate: 5500,
    currency: 'THB',
  })
  console.log('Created matter:', mKim.matterNumber)

  // ── Hearings ───────────────────────────────────────────────────
  await post('/hearings', {
    matterId: mSmith._id,
    clientFolderId: james._id,
    date: daysFromNow(0),
    time: '09:30',
    hearingType: 'mention',
    court: 'Civil Court Division 3',
    room: '4B',
    judge: 'Somchai Pattanarat',
    notes: 'TM.7 status review',
  })

  await post('/hearings', {
    matterId: mChang._id,
    clientFolderId: changCorp._id,
    date: daysFromNow(2),
    time: '14:00',
    hearingType: 'trial',
    court: 'Civil Court Division 1',
    room: '2A',
    judge: 'Wirut Arayachai',
    notes: 'First witness examination',
  })

  await post('/hearings', {
    matterId: mKim._id,
    clientFolderId: jiwoo._id,
    date: daysFromNow(5),
    time: '10:00',
    hearingType: 'mention',
    court: 'Labour Court',
    notes: 'Case management conference',
  })

  await post('/hearings', {
    matterId: mNexus._id,
    clientFolderId: nexus._id,
    date: daysFromNow(8),
    time: '13:30',
    hearingType: 'other',
    court: 'BOI Head Office',
    notes: 'BOI documentation submission',
  })

  console.log('Created 4 hearings')

  // ── Time entries ───────────────────────────────────────────────
  const entries = [
    { matterId: mSmith._id, clientFolderId: james._id, durationMinutes: 90, description: 'TM.7 document review and preparation', ratePerHour: 5000 },
    { matterId: mSmith._id, clientFolderId: james._id, durationMinutes: 60, description: 'Client consultation re visa conditions', ratePerHour: 5000 },
    { matterId: mNexus._id, clientFolderId: nexus._id, durationMinutes: 180, description: 'BOI application drafting', ratePerHour: 6000 },
    { matterId: mNexus._id, clientFolderId: nexus._id, durationMinutes: 120, description: 'Due diligence review', ratePerHour: 6000 },
    { matterId: mChang._id, clientFolderId: changCorp._id, durationMinutes: 240, description: 'Witness preparation', ratePerHour: 6000 },
    { matterId: mChang._id, clientFolderId: changCorp._id, durationMinutes: 90, description: 'Court filing — statement of claim', ratePerHour: 6000 },
    { matterId: mSiriwan._id, clientFolderId: siriwan._id, durationMinutes: 60, description: 'Chanote title search and verification', ratePerHour: 5000 },
    { matterId: mKim._id, clientFolderId: jiwoo._id, durationMinutes: 120, description: 'Employment contract review', ratePerHour: 5500 },
    { matterId: mKim._id, clientFolderId: jiwoo._id, durationMinutes: 60, description: 'Response to opposing counsel letter', ratePerHour: 5500 },
  ]

  for (const e of entries) {
    await post('/time-entries', {
      ...e,
      date: daysFromNow(-Math.floor(Math.random() * 7)),
      attorney: 'attorney-001',
      currency: 'THB',
    })
  }
  console.log('Created 9 time entries')

  // ── Retainer transactions ──────────────────────────────────────
  await post(`/client-folders/${james._id}/retainer/transactions`, {
    type: 'deposit', amount: 50000, description: 'Retainer intake — immigration matters',
  })
  await post(`/client-folders/${nexus._id}/retainer/transactions`, {
    type: 'deposit', amount: 120000, description: 'Retainer intake — BOI matter',
  })
  await post(`/client-folders/${changCorp._id}/retainer/transactions`, {
    type: 'deposit', amount: 40000, description: 'Retainer intake — litigation',
  })
  await post(`/client-folders/${changCorp._id}/retainer/transactions`, {
    type: 'deduction', amount: 28000, description: 'Court fees and disbursements',
  })
  await post(`/client-folders/${kenji._id}/retainer/transactions`, {
    type: 'deposit', amount: 25000, description: 'Retainer intake',
  })
  await post(`/client-folders/${kenji._id}/retainer/transactions`, {
    type: 'deduction', amount: 17000, description: 'Immigration fees applied',
  })
  console.log('Created retainer transactions')

  console.log('\nSeed complete.')
}

main().catch(err => {
  console.error(err)
  process.exit(1)
})
