import { describe, expect, it } from 'vitest'
import {
  canEdit, canMove, changedFields, devTaskCreateSchema, devTaskUpdateSchema, groupByStatus, parseTaskRef, positionForPlacement,
  positionForUrgency, sortColumn, statusTimestamps, taskRef, type DevTask,
} from '@/lib/domain/dev-tasks'
import { newBoardKey, parseKeyHashes, sha256Hex, verifyBoardKey } from '@/lib/integrations/dev-task-keys'

let n = 0
const task = (over: Partial<DevTask>): DevTask => ({
  id: `id-${++n}`, task_number: n, project: 'HHA Workspace', title: `Task ${n}`, summary: null, urgency: 'normal', status: 'pending',
  position: n * 1024, why: null, steps: [], done_when: null, report_back: null, do_not_touch: null, details: null, due_date: null,
  source: 'api', created_by: null, started_at: null, completed_at: null, completion_note: null, archived_at: null,
  created_at: '2026-10-21T00:00:00Z', updated_at: '2026-10-21T00:00:00Z', ...over,
})

describe('task placement by urgency', () => {
  const column = [task({ urgency: 'urgent', position: 1000 }), task({ urgency: 'high', position: 2000 }), task({ urgency: 'normal', position: 3000 }), task({ urgency: 'low', position: 4000 })]

  it('puts a new task after every task at least as urgent and before the less urgent ones', () => {
    expect(positionForUrgency(column, 'urgent')).toBe(1500)
    expect(positionForUrgency(column, 'high')).toBe(2500)
    expect(positionForUrgency(column, 'normal')).toBe(3500)
    expect(positionForUrgency(column, 'low')).toBe(4000 + 1024)
  })

  it('puts an urgent task at the very top when nothing is urgent yet, and handles an empty column', () => {
    expect(positionForUrgency(column.slice(1), 'urgent')).toBeLessThan(2000)
    expect(positionForUrgency([], 'normal')).toBe(1024)
  })

  it('places a task before, after, at the top or at the bottom', () => {
    const [a, b, c] = column
    expect(positionForPlacement(column, { before: b.id })).toBe(1500)
    expect(positionForPlacement(column, { after: b.id })).toBe(2500)
    expect(positionForPlacement(column, { before: a.id })).toBeLessThan(1000)
    expect(positionForPlacement(column, { edge: 'bottom' })).toBeGreaterThan(4000)
    expect(positionForPlacement(column, { edge: 'top' })).toBeLessThan(1000)
    expect(positionForPlacement(column, { after: 'missing' })).toBeNull()
    expect(c).toBeDefined()
  })
})

describe('who may move a task', () => {
  it('lets the developer start, put back, finish and reopen, but not skip or un-finish to pending', () => {
    expect(canMove('developer', 'pending', 'ongoing')).toBe(true)
    expect(canMove('developer', 'ongoing', 'pending')).toBe(true)
    expect(canMove('developer', 'ongoing', 'completed')).toBe(true)
    expect(canMove('developer', 'completed', 'ongoing')).toBe(true)
    expect(canMove('developer', 'pending', 'completed')).toBe(false)
    expect(canMove('developer', 'completed', 'pending')).toBe(false)
  })

  it('lets the manager move anything and edit; the developer never edits', () => {
    expect(canMove('manager', 'pending', 'completed')).toBe(true)
    expect(canMove('manager', 'completed', 'pending')).toBe(true)
    expect(canEdit('manager')).toBe(true)
    expect(canEdit('developer')).toBe(false)
  })

  it('sets and clears the start and finish times with each move', () => {
    const now = '2026-10-21T15:00:00Z'
    expect(statusTimestamps({ started_at: null, completed_at: null }, 'ongoing', now)).toEqual({ started_at: now, completed_at: null })
    expect(statusTimestamps({ started_at: '2026-10-20T10:00:00Z', completed_at: null }, 'completed', now)).toEqual({ started_at: '2026-10-20T10:00:00Z', completed_at: now })
    expect(statusTimestamps({ started_at: '2026-10-20T10:00:00Z', completed_at: now }, 'pending', now)).toEqual({ started_at: null, completed_at: null })
  })
})

describe('board order', () => {
  it('orders pending and ongoing by position, completed newest first, and hides removed tasks', () => {
    const tasks = [
      task({ position: 3 }), task({ position: 1 }), task({ status: 'ongoing', position: 5 }),
      task({ status: 'completed', completed_at: '2026-10-20T00:00:00Z' }), task({ status: 'completed', completed_at: '2026-10-21T00:00:00Z' }),
      task({ archived_at: '2026-10-21T00:00:00Z' }),
    ]
    const board = groupByStatus(tasks)
    expect(board.pending.map((t) => t.position)).toEqual([1, 3])
    expect(board.ongoing).toHaveLength(1)
    expect(board.completed.map((t) => t.completed_at)).toEqual(['2026-10-21T00:00:00Z', '2026-10-20T00:00:00Z'])
    expect(sortColumn([])).toEqual([])
  })
})

describe('task references and input', () => {
  it('reads T-12, t12, 12 and an id', () => {
    expect(parseTaskRef('T-12')).toEqual({ number: 12 })
    expect(parseTaskRef('t12')).toEqual({ number: 12 })
    expect(parseTaskRef('12')).toEqual({ number: 12 })
    expect(parseTaskRef('0f8fad5b-d9cb-469f-a165-70867728950e')).toEqual({ id: '0f8fad5b-d9cb-469f-a165-70867728950e' })
    expect(parseTaskRef('drop table')).toBeNull()
    expect(taskRef({ task_number: 7 })).toBe('T-7')
  })

  it('accepts a full brief with defaults and refuses a bad one', () => {
    const ok = devTaskCreateSchema.parse({ title: 'Deploy main', steps: ['Deploy', 'Check crons'], why: '  ', due_date: '2026-10-22' })
    expect(ok).toMatchObject({ project: 'HHA Workspace', urgency: 'normal', steps: ['Deploy', 'Check crons'], why: null })
    expect(devTaskCreateSchema.safeParse({ title: 'x' }).success).toBe(false)
    expect(devTaskCreateSchema.safeParse({ title: 'Deploy', urgency: 'asap' }).success).toBe(false)
    expect(devTaskUpdateSchema.safeParse({ place: { before: 'T-3' } }).success).toBe(true)
    expect(devTaskUpdateSchema.safeParse({ status: 'done' }).success).toBe(false)
  })

  it('lists only the fields that really changed', () => {
    expect(changedFields({ title: 'A', steps: ['1'] }, { title: 'A', steps: ['1', '2'] })).toEqual(['steps'])
  })
})

describe('board keys', () => {
  it('accepts a key whose SHA-256 is configured and refuses anything else', () => {
    const { key, sha256 } = newBoardKey()
    const other = newBoardKey()
    expect(sha256).toBe(sha256Hex(key))
    expect(verifyBoardKey(`Bearer ${key}`, `${other.sha256}, ${sha256}`)).toBe(true)
    expect(verifyBoardKey(`Bearer ${other.key}`, sha256)).toBe(false)
    expect(verifyBoardKey(`Bearer ${key}`, '')).toBe(false)
    expect(verifyBoardKey(null, sha256)).toBe(false)
    expect(verifyBoardKey(`Bearer ${sha256}`, sha256)).toBe(false)
    expect(parseKeyHashes(`nothex, ${sha256.toUpperCase()}`)).toEqual([sha256])
  })
})
