import { describe, expect, it } from 'vitest'
import { mapAttribute, mapProduct, parseMagentoDate, toMagentoDate } from './mappers.js'

describe('mappers', () => {
  it('round-trips Magento UTC timestamps', () => {
    const d = parseMagentoDate('2026-10-08 09:15:00')!
    expect(d.toISOString()).toBe('2026-10-08T09:15:00.000Z')
    expect(toMagentoDate(d)).toBe('2026-10-08 09:15:00')
  })

  it('splits grouped children from link types, resolves configurable children and lifts special price', () => {
    const rec = mapProduct(
      {
        id: 10, sku: 'TEE', name: 'Tee', attribute_set_id: 4, price: 20, status: 1, visibility: 4, type_id: 'configurable',
        created_at: '2026-01-01 00:00:00', updated_at: '2026-10-01 10:00:00',
        extension_attributes: { website_ids: [1], configurable_product_links: [11, 99], category_links: [{ category_id: '3', position: 1 }] },
        product_links: [
          { sku: 'TEE', link_type: 'related', linked_product_sku: 'MUG', linked_product_type: 'simple', position: 0 },
          { sku: 'TEE', link_type: 'associated', linked_product_sku: 'PART', linked_product_type: 'simple', position: 0 },
        ],
        media_gallery_entries: [{ id: 1, media_type: 'image', label: '', position: 1, disabled: false, types: ['image'], file: '/t/e/tee.jpg' }],
        custom_attributes: [
          { attribute_code: 'special_price', value: '15.0000' },
          { attribute_code: 'special_from_date', value: '2026-10-01 00:00:00' },
          { attribute_code: 'description', value: '<p>Soft</p>' },
        ],
      },
      new Map([[11, 'TEE-S']]),
    )
    expect(rec.relations).toEqual([{ childSku: 'TEE-S', kind: 'configurable' }, { childSku: 'PART', kind: 'grouped' }])
    expect(rec.links).toEqual([{ linkType: 'related', linkedSku: 'MUG', position: 0 }])
    expect(rec.product).toMatchObject({ specialPrice: 15, specialFrom: '2026-10-01', websiteIds: [1] })
    expect(rec.storeData).toMatchObject({ storeId: 0, description: '<p>Soft</p>', attributes: { special_price: '15.0000' } })
    expect(rec.images[0]).toMatchObject({ label: null, roles: ['image'] })
  })

  it('drops the blank placeholder option Magento adds to select attributes', () => {
    const row = mapAttribute({ attribute_id: 1, attribute_code: 'color', frontend_input: 'select', is_required: false, is_user_defined: true, options: [{ label: ' ', value: '' }, { label: 'Red', value: '5' }] })
    expect(row.options).toEqual([{ value: '5', label: 'Red' }])
  })
})
