import { describe, expect, it } from 'vitest'
import {
  buildTrainingUnitSavePayload,
  createEmptyTrainingUnitFormData,
  trainingUnitFormSnapshot,
  validateTrainingUnitFormForSave,
} from './trainingUnitEditorCore.js'

describe('trainingUnitEditorCore', () => {
  it('createEmptyTrainingUnitFormData defaults', () => {
    const fd = createEmptyTrainingUnitFormData({ groupId: '2', plannedDate: '2026-05-01' })
    expect(fd.group_id).toBe('2')
    expect(fd.planned_date).toBe('2026-05-01')
    expect(fd.sections).toHaveLength(1)
    expect(fd.sections[0].title).toBe('Hauptteil')
  })

  it('validateTrainingUnitFormForSave', () => {
    expect(validateTrainingUnitFormForSave({ group_id: '', planned_date: '' }).ok).toBe(false)
    expect(validateTrainingUnitFormForSave({ group_id: '1', planned_date: '2026-01-01' }).ok).toBe(true)
  })

  it('buildTrainingUnitSavePayload create includes group and template', () => {
    const formData = createEmptyTrainingUnitFormData({ groupId: '5', plannedDate: '2026-05-10' })
    const payload = buildTrainingUnitSavePayload(formData, { draftPlanTemplateId: '9' })
    expect(payload.group_id).toBe(5)
    expect(payload.plan_template_id).toBe(9)
    expect(payload.planned_date).toBe('2026-05-10')
    expect(payload.sections).toBeDefined()
  })

  it('buildTrainingUnitSavePayload update sets debrief and clears lead when empty', () => {
    const formData = {
      ...createEmptyTrainingUnitFormData({ groupId: '5', plannedDate: '2026-05-10' }),
      status: 'completed',
      debrief_completed: true,
      lead_trainer_profile_id: '',
      session_assistants_inherit: true,
    }
    const payload = buildTrainingUnitSavePayload(formData, { editingUnit: { id: 1 } })
    expect(payload.debrief_completed).toBe(true)
    expect(payload.lead_trainer_profile_id).toBeNull()
    expect(payload.assistant_trainer_profile_ids).toBeNull()
    expect(payload.group_id).toBeUndefined()
  })

  it('trainingUnitFormSnapshot matches save payload', () => {
    const formData = createEmptyTrainingUnitFormData({ groupId: '5', plannedDate: '2026-05-10' })
    const snap = trainingUnitFormSnapshot(formData, { draftPlanTemplateId: '3' })
    const payload = buildTrainingUnitSavePayload(formData, { draftPlanTemplateId: '3' })
    expect(snap).toBe(JSON.stringify(payload))
  })
})
