import { describe, expect, it } from 'vitest'
import ExcelJS from 'exceljs'
import { buildProjectCopilotXlsx } from '../internal/project-xlsx'
import type { ProjectExportInput } from '../internal/project-types'

function input(overrides: Partial<ProjectExportInput> = {}): ProjectExportInput {
  return {
    stammdaten: {
      supplierName: 'Musterzulieferer GmbH',
      plantLocation: 'Musterstadt',
      productName: 'Achsträger',
      projectCode: 'PRJ-001',
      vehicleProject: 'G99',
      productLine: 'Fahrwerk',
      visitDate: '2026-07-01',
      orderReceivedDate: '2026-06-01',
      expectedEndDate: '2026-12-01',
      customerTaktTimeSec: 60,
      targetCycleTimeSec: 55,
      plannedOee: 85,
      notes: 'Testnotiz',
      isDemo: false,
    },
    agendas: [
      {
        title: 'Werksbesuch Juli',
        language: 'de',
        status: 'final',
        days: [
          {
            title: 'Tag 1',
            date: '2026-07-01',
            items: [{ startTime: '09:00', endTime: '10:00', title: 'Begrüßung & Rundgang', responsible: 'Team Lead', location: 'Halle 1' }],
          },
        ],
      },
    ],
    workshopActions: [
      {
        actionNumber: 1,
        area: 'Montage',
        description: 'Werkzeugwechselzeit reduzieren',
        effort: 'middle',
        benefit: 'high',
        status: 'open',
        responsible: 'M. Muster',
        targetDate: '2026-08-01',
      },
    ],
    moduleSummaries: [{ label: 'Fabrikanalyse', countLabel: '1 Assessment', items: ['Werksbesuch Musterwerk — Ø 2,80 (In Bearbeitung)'] }],
    generatedAtLabel: '19.07.2026, 10:00',
    ...overrides,
  }
}

describe('buildProjectCopilotXlsx', () => {
  it('produces a real XLSX with the expected sheets and roundtrips through exceljs', async () => {
    const buffer = await buildProjectCopilotXlsx(input())
    expect(buffer.byteLength).toBeGreaterThan(0)

    const wb = new ExcelJS.Workbook()
    await wb.xlsx.load(buffer as ArrayBuffer)

    const sheetNames = wb.worksheets.map((ws) => ws.name)
    expect(sheetNames).toEqual(['Anleitung', 'Stammdaten', 'Agenda', 'Maßnahmen', 'Modulübersicht'])

    const stamm = wb.getWorksheet('Stammdaten')!
    const supplierRow = stamm.getRows(1, stamm.rowCount) ?? []
    expect(supplierRow.some((r) => r.getCell(1).text === 'Zulieferer' && r.getCell(2).text === 'Musterzulieferer GmbH')).toBe(true)

    const agenda = wb.getWorksheet('Agenda')!
    expect(agenda.getRow(1).getCell(1).text).toBe('Agenda')
    const agendaRows = agenda.getRows(2, agenda.rowCount) ?? []
    expect(agendaRows.some((r) => r.getCell(5).text === 'Begrüßung & Rundgang')).toBe(true)

    const actions = wb.getWorksheet('Maßnahmen')!
    const actionRows = actions.getRows(2, actions.rowCount) ?? []
    expect(actionRows.some((r) => r.getCell(3).text === 'Werkzeugwechselzeit reduzieren')).toBe(true)

    const info = wb.getWorksheet('Anleitung')!
    const infoText = (info.getRows(1, info.rowCount) ?? []).map((r) => r.getCell(1).text + ' ' + r.getCell(2).text).join('\n')
    expect(infoText).toContain('Lean Shop-floor Cycle')
  })

  it('handles a project with no agenda/actions/module data — empty-state markers instead of throwing (PR #346 review fix)', async () => {
    const buffer = await buildProjectCopilotXlsx(input({ agendas: [], workshopActions: [], moduleSummaries: [] }))
    const wb = new ExcelJS.Workbook()
    await wb.xlsx.load(buffer as ArrayBuffer)

    const textOf = (sheetName: string) => {
      const ws = wb.getWorksheet(sheetName)!
      return (ws.getRows(1, ws.rowCount) ?? [])
        .map((r) => [1, 2, 3].map((c) => r.getCell(c).text).join(' '))
        .join('\n')
    }
    expect(textOf('Agenda')).toContain('(keine Agenda angelegt)')
    expect(textOf('Maßnahmen')).toContain('(keine Maßnahmen erfasst)')
    expect(textOf('Modulübersicht')).toContain('(keine Modul-Daten für dieses Projekt)')
  })

  it('includes the fictional-data disclaimer sheet content only when is_demo is true', async () => {
    const withDemo = await buildProjectCopilotXlsx(input({ stammdaten: { ...input().stammdaten, isDemo: true } }))
    const withoutDemo = await buildProjectCopilotXlsx(input())

    const wbDemo = new ExcelJS.Workbook()
    await wbDemo.xlsx.load(withDemo as ArrayBuffer)
    const infoDemo = wbDemo.getWorksheet('Anleitung')!
    const demoText = (infoDemo.getRows(1, infoDemo.rowCount) ?? []).map((r) => r.getCell(1).text).join('\n')
    expect(demoText).toContain('Demo-Hinweis')

    const wbNoDemo = new ExcelJS.Workbook()
    await wbNoDemo.xlsx.load(withoutDemo as ArrayBuffer)
    const infoNoDemo = wbNoDemo.getWorksheet('Anleitung')!
    const noDemoText = (infoNoDemo.getRows(1, infoNoDemo.rowCount) ?? []).map((r) => r.getCell(1).text).join('\n')
    expect(noDemoText).not.toContain('Demo-Hinweis')
  })
})
