import { createHmac } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { hhaSigningPayload, parseSynchronError, signHhaRequest } from '@/lib/integrations/synchron-signing'

const secret = 'k'.repeat(40)
const hmac = (s: string) => createHmac('sha256', secret).update(s).digest('hex')

describe('signing calls to Synchron (contract v0.2.0)', () => {
  it('signs timestamp + "." + the exact body for POST', () => {
    const body = '{"items":[{"hha_permit_id":"p_1"}]}'
    const h = signHhaRequest({ method: 'POST', path: '/api/v1/hha/route-purchases', body, secret, nowSeconds: 1760745600 })
    expect(h['X-HHA-Timestamp']).toBe('1760745600')
    expect(h['X-HHA-Signature']).toBe(hmac(`1760745600.${body}`))
    expect(h['X-HHA-Signature']).toMatch(/^[0-9a-f]{64}$/)
  })
  it('signs "GET " + path + "?" + query for GET, keeping the "?" when the query is empty', () => {
    expect(hhaSigningPayload({ method: 'GET', path: '/api/v1/hha/route-purchases/hhp_1' })).toBe('GET /api/v1/hha/route-purchases/hhp_1?')
    expect(hhaSigningPayload({ method: 'get', path: '/api/v1/hha/x', query: 'a=1&b=2' })).toBe('GET /api/v1/hha/x?a=1&b=2')
    const h = signHhaRequest({ method: 'GET', path: '/api/v1/hha/x', secret, nowSeconds: 1760745600 })
    expect(h['X-HHA-Signature']).toBe(hmac('1760745600.GET /api/v1/hha/x?'))
  })
  it('refuses a full URL instead of a path, and a missing secret', () => {
    expect(() => hhaSigningPayload({ method: 'GET', path: 'https://synchron.example/api/v1/hha/x' })).toThrow()
    expect(() => signHhaRequest({ method: 'POST', path: '/api/v1/hha/x', body: '{}', secret: 'short' })).toThrow()
  })
})

describe('Synchron error format', () => {
  it('reads error, message, request_id and details', () => {
    expect(parseSynchronError({ error: 'items_unavailable', message: 'Taken', request_id: 'req_1', details: { unavailable_items: [] } }))
      .toEqual({ error: 'items_unavailable', message: 'Taken', requestId: 'req_1', details: { unavailable_items: [] } })
  })
  it('returns null for anything that is not that shape', () => {
    expect(parseSynchronError({ ok: true })).toBeNull()
    expect(parseSynchronError(null)).toBeNull()
  })
})
