import { afterEach, beforeEach, describe, expect, it } from 'vitest'

import {
  buildMigrationPatch,
  clearLegacyStorage,
} from '@/lib/user-settings-migration'

function clearAllCookies() {
  for (const part of document.cookie.split(';')) {
    const eq = part.indexOf('=')
    const name = (eq < 0 ? part : part.slice(0, eq)).trim()
    if (name) document.cookie = `${name}=; max-age=0; path=/`
  }
}

beforeEach(() => {
  localStorage.clear()
  clearAllCookies()
})

afterEach(() => {
  localStorage.clear()
  clearAllCookies()
})

describe('buildMigrationPatch', () => {
  it('returns no data when nothing is stored', () => {
    const result = buildMigrationPatch()
    expect(result.hasData).toBe(false)
    expect(result.patch).toEqual({})
    expect(result.legacyKeys).toEqual([])
  })

  it('skips after marker is set to current version', () => {
    localStorage.setItem('scrum4me:sprint_pb_filter_status', 'all')
    localStorage.setItem('scrum4me:settings_migrated', 'v2')
    const result = buildMigrationPatch()
    expect(result.hasData).toBe(false)
  })

  it('still runs when only the v1 marker is set (re-migration)', () => {
    localStorage.setItem('scrum4me:sprint_pb_filter_status', 'all')
    localStorage.setItem('scrum4me:settings_migrated', 'v1')
    const result = buildMigrationPatch()
    expect(result.hasData).toBe(true)
  })

  it('extracts split-pane cookies into layout', () => {
    document.cookie = `sp:backlog-p1=${encodeURIComponent(JSON.stringify([25, 35, 40]))}; path=/`
    const result = buildMigrationPatch()
    expect(result.patch.layout?.splitPanePositions).toEqual({ 'backlog-p1': [25, 35, 40] })
    expect(result.legacyCookies).toContain('sp:backlog-p1')
  })

  it('ignores split-pane cookies that do not sum to 100', () => {
    document.cookie = `sp:bad=${encodeURIComponent(JSON.stringify([10, 20]))}; path=/`
    const result = buildMigrationPatch()
    expect(result.patch.layout).toBeUndefined()
  })

  it('extracts active-sprint cookies into layout.activeSprints', () => {
    document.cookie = `active_sprint_prod-1=sprint-abc; path=/`
    document.cookie = `active_sprint_prod-2=sprint-xyz; path=/`
    const result = buildMigrationPatch()
    expect(result.patch.layout?.activeSprints).toEqual({
      'prod-1': 'sprint-abc',
      'prod-2': 'sprint-xyz',
    })
    expect(result.legacyCookies).toContain('active_sprint_prod-1')
  })

  it('extracts sprint backlog prefs into nested patch', () => {
    localStorage.setItem('scrum4me:sprint_pb_filter_status', 'all')
    localStorage.setItem('scrum4me:sprint_pb_sort', 'priority')
    localStorage.setItem('scrum4me:sprint_pb_sort_dir', 'desc')
    localStorage.setItem('scrum4me:sprint_pb_collapsed', JSON.stringify(['pbi-1', 'pbi-2']))
    localStorage.setItem('scrum4me:sprint_pb_filter_popover_open', 'true')

    const result = buildMigrationPatch()

    expect(result.hasData).toBe(true)
    expect(result.patch.views?.sprintBacklog).toEqual({
      filterStatus: 'all',
      sort: 'priority',
      sortDir: 'desc',
      collapsedPbis: ['pbi-1', 'pbi-2'],
      filterPopoverOpen: true,
    })
    expect(result.legacyKeys).toContain('scrum4me:sprint_pb_filter_status')
    expect(result.legacyKeys).toContain('scrum4me:sprint_pb_collapsed')
  })

  it('extracts pbi-list prefs', () => {
    localStorage.setItem('scrum4me:pbi_sort', 'date')
    localStorage.setItem('scrum4me:pbi_filter_priority', '2')

    const result = buildMigrationPatch()
    expect(result.patch.views?.pbiList).toEqual({ sort: 'date', filterPriority: 2 })
  })

  it('extracts story_sort', () => {
    localStorage.setItem('scrum4me:story_sort', 'code')
    const result = buildMigrationPatch()
    expect(result.patch.views?.storyPanel).toEqual({ sort: 'code' })
  })

  it('extracts debug-mode', () => {
    localStorage.setItem('scrum4me:debug-mode', 'true')
    const result = buildMigrationPatch()
    expect(result.patch.devTools).toEqual({ debugMode: true })
  })

  it('extracts jobs-column dynamic prefixes from CSV values', () => {
    localStorage.setItem('queue_filter_kind', 'TASK_IMPLEMENTATION,SPRINT_IMPLEMENTATION')
    localStorage.setItem('queue_filter_status', 'queued,running')

    const result = buildMigrationPatch()
    expect(result.patch.views?.jobsColumns?.['queue']).toEqual({
      kinds: ['TASK_IMPLEMENTATION', 'SPRINT_IMPLEMENTATION'],
      statuses: ['queued', 'running'],
    })
  })

  it('ignores invalid enum values', () => {
    localStorage.setItem('scrum4me:sprint_pb_filter_status', 'BOGUS')
    const result = buildMigrationPatch()
    expect(result.hasData).toBe(false)
  })
})

describe('clearLegacyStorage', () => {
  it('removes given keys and cookies and sets the v2 marker', () => {
    localStorage.setItem('scrum4me:sprint_pb_sort', 'code')
    document.cookie = 'sp:x=foo; path=/'

    clearLegacyStorage(['scrum4me:sprint_pb_sort'], ['sp:x'])

    expect(localStorage.getItem('scrum4me:sprint_pb_sort')).toBeNull()
    expect(document.cookie).not.toContain('sp:x=foo')
    expect(localStorage.getItem('scrum4me:settings_migrated')).toBe('v2')
  })

  it('sets marker even with empty lists (no-op migration)', () => {
    clearLegacyStorage([], [])
    expect(localStorage.getItem('scrum4me:settings_migrated')).toBe('v2')
  })
})
