import { describe, expect, test } from 'vitest'
import {
  buildSchemaJson,
  diffSchemas,
  hasBreakingChanges,
  parseSchemaJson,
  suggestVersionBump,
  type PropertyDef,
} from './types'

const prop = (overrides: Partial<PropertyDef>): PropertyDef => ({
  id: 'p1',
  name: 'field',
  kind: 'string',
  required: false,
  unique: false,
  ...overrides,
})

describe('buildSchemaJson', () => {
  test('добавляет $schema, type, additionalProperties:false', () => {
    const s = buildSchemaJson([])
    expect(s.$schema).toContain('json-schema.org')
    expect(s.type).toBe('object')
    expect(s.additionalProperties).toBe(false)
  })

  test('пропускает property без имени', () => {
    const s = buildSchemaJson([prop({ name: '' })])
    expect(s.properties).toEqual({})
  })

  test('собирает required только из required:true', () => {
    const s = buildSchemaJson([
      prop({ name: 'a', required: true }),
      prop({ name: 'b', required: false }),
    ])
    expect(s.required).toEqual(['a'])
  })

  test('emit string поле с min/max/pattern', () => {
    const s = buildSchemaJson([prop({
      name: 'code',
      kind: 'string',
      minLength: 1,
      maxLength: 32,
      pattern: '^[A-Z]+$',
    })])
    const f = s.properties!.code
    expect(f.type).toBe('string')
    expect(f.minLength).toBe(1)
    expect(f.maxLength).toBe(32)
    expect(f.pattern).toBe('^[A-Z]+$')
  })

  test('emit enum поле с string values', () => {
    const s = buildSchemaJson([prop({ name: 'status', kind: 'enum', enumValues: ['ACTIVE', 'INACTIVE'] })])
    const f = s.properties!.status
    expect(f.type).toBe('string')
    expect(f.enum).toEqual(['ACTIVE', 'INACTIVE'])
  })

  test('emit localized как object с x-localized + patternProperties', () => {
    const s = buildSchemaJson([prop({ name: 'name', kind: 'localized' })])
    const f = s.properties!.name as Record<string, unknown>
    expect(f.type).toBe('object')
    expect(f['x-localized']).toBe(true)
    expect(f.patternProperties).toBeDefined()
  })

  test('emit date / datetime через format', () => {
    const s = buildSchemaJson([
      prop({ name: 'launch', kind: 'date' }),
      prop({ name: 'epoch', kind: 'datetime' }),
    ])
    expect(s.properties!.launch.format).toBe('date')
    expect(s.properties!.epoch.format).toBe('date-time')
  })

  test('x-unique=true emit\'ит x-unique в schema', () => {
    const s = buildSchemaJson([prop({ name: 'code', kind: 'string', unique: true })])
    expect((s.properties!.code as Record<string, unknown>)['x-unique']).toBe(true)
  })

  test('x-id-source emit\'ится в root schema', () => {
    const s = buildSchemaJson(
      [prop({ name: 'code', kind: 'string' })],
      'code',
    )
    expect((s as Record<string, unknown>)['x-id-source']).toBe('code')
  })

  test('пустой idSource не emit\'ится', () => {
    const s = buildSchemaJson([prop({ name: 'code', kind: 'string' })])
    expect((s as Record<string, unknown>)['x-id-source']).toBeUndefined()
  })
})

describe('parseSchemaJson roundtrip', () => {
  test('build → parse возвращает эквивалентный набор properties', () => {
    const original: PropertyDef[] = [
      prop({ id: '1', name: 'code', kind: 'string', required: true, minLength: 1, maxLength: 32 }),
      prop({ id: '2', name: 'name', kind: 'localized', required: true }),
      prop({ id: '3', name: 'status', kind: 'enum', enumValues: ['ACTIVE'] }),
      prop({ id: '4', name: 'mass', kind: 'number', minimum: 0, maximum: 100 }),
      prop({ id: '5', name: 'enabled', kind: 'boolean' }),
      prop({ id: '6', name: 'tags', kind: 'array_string', uniqueItems: true }),
      prop({ id: '7', name: 'launched', kind: 'date' }),
      prop({ id: '8', name: 'epoch', kind: 'datetime' }),
    ]
    const json = buildSchemaJson(original, 'code')
    const parsed = parseSchemaJson(json)

    expect(parsed.idSource).toBe('code')
    expect(parsed.properties).toHaveLength(original.length)

    const byName = (key: string) => parsed.properties.find((p) => p.name === key)!
    expect(byName('code').kind).toBe('string')
    expect(byName('code').required).toBe(true)
    expect(byName('code').minLength).toBe(1)
    expect(byName('name').kind).toBe('localized')
    expect(byName('status').kind).toBe('enum')
    expect(byName('status').enumValues).toEqual(['ACTIVE'])
    expect(byName('mass').kind).toBe('number')
    expect(byName('mass').minimum).toBe(0)
    expect(byName('enabled').kind).toBe('boolean')
    expect(byName('tags').kind).toBe('array_string')
    expect(byName('tags').uniqueItems).toBe(true)
    expect(byName('launched').kind).toBe('date')
    expect(byName('epoch').kind).toBe('datetime')
  })

  test('сохраняет x-unique через roundtrip', () => {
    const json = buildSchemaJson([prop({ name: 'code', kind: 'string', unique: true })])
    const parsed = parseSchemaJson(json)
    expect(parsed.properties[0].unique).toBe(true)
  })

  test('reference kind roundtrip — emit x-references + parse обратно', () => {
    const json = buildSchemaJson([
      prop({
        name: 'status',
        kind: 'reference',
        referenceTarget: 'spacecraft_status.code',
        required: true,
      }),
    ])
    // build emit'ит x-references
    expect((json.properties!.status as Record<string, unknown>)['x-references']).toBe(
      'spacecraft_status.code',
    )
    // parse → recovers reference kind, не fallback на opaque/string
    const parsed = parseSchemaJson(json)
    expect(parsed.properties[0].kind).toBe('reference')
    expect(parsed.properties[0].referenceTarget).toBe('spacecraft_status.code')
  })

  test('пустой schema → пустой результат', () => {
    expect(parseSchemaJson(undefined)).toEqual({ properties: [], idSource: undefined })
  })
})

describe('diffSchemas — breaking detection', () => {
  test('identical schemas → нет изменений', () => {
    const s = buildSchemaJson([prop({ name: 'a', kind: 'string' })])
    expect(diffSchemas(s, s)).toEqual([])
  })

  test('removed property → breaking', () => {
    const before = buildSchemaJson([prop({ name: 'a', kind: 'string' })])
    const after = buildSchemaJson([])
    const changes = diffSchemas(before, after)
    expect(changes).toHaveLength(1)
    expect(changes[0].severity).toBe('breaking')
    expect(changes[0].field).toBe('a')
  })

  test('type changed → breaking', () => {
    const before = buildSchemaJson([prop({ name: 'a', kind: 'string' })])
    const after = buildSchemaJson([prop({ name: 'a', kind: 'integer' })])
    const changes = diffSchemas(before, after)
    expect(changes.some((c) => c.severity === 'breaking' && c.reason.includes('type'))).toBe(true)
  })

  test('became required → breaking', () => {
    const before = buildSchemaJson([prop({ name: 'a', kind: 'string', required: false })])
    const after = buildSchemaJson([prop({ name: 'a', kind: 'string', required: true })])
    expect(diffSchemas(before, after).some((c) => c.severity === 'breaking' && c.reason === 'now required')).toBe(true)
  })

  test('became optional → compatible', () => {
    const before = buildSchemaJson([prop({ name: 'a', kind: 'string', required: true })])
    const after = buildSchemaJson([prop({ name: 'a', kind: 'string', required: false })])
    expect(diffSchemas(before, after).some((c) => c.severity === 'compatible' && c.reason === 'now optional')).toBe(true)
  })

  test('enum value removed → breaking', () => {
    const before = buildSchemaJson([prop({ name: 's', kind: 'enum', enumValues: ['A', 'B'] })])
    const after = buildSchemaJson([prop({ name: 's', kind: 'enum', enumValues: ['A'] })])
    expect(diffSchemas(before, after).some((c) => c.severity === 'breaking' && c.reason.includes('enum'))).toBe(true)
  })

  test('enum value added → compatible', () => {
    const before = buildSchemaJson([prop({ name: 's', kind: 'enum', enumValues: ['A'] })])
    const after = buildSchemaJson([prop({ name: 's', kind: 'enum', enumValues: ['A', 'B'] })])
    expect(diffSchemas(before, after).some((c) => c.severity === 'compatible' && c.reason.includes('enum'))).toBe(true)
  })

  test('maxLength tightened → breaking', () => {
    const before = buildSchemaJson([prop({ name: 'a', kind: 'string', maxLength: 100 })])
    const after = buildSchemaJson([prop({ name: 'a', kind: 'string', maxLength: 50 })])
    expect(diffSchemas(before, after).some((c) => c.severity === 'breaking' && c.reason.includes('maxLength'))).toBe(true)
  })

  test('новое required поле → breaking', () => {
    const before = buildSchemaJson([])
    const after = buildSchemaJson([prop({ name: 'new', kind: 'string', required: true })])
    expect(diffSchemas(before, after).some((c) => c.severity === 'breaking' && c.reason.includes('new required'))).toBe(true)
  })

  test('новое optional поле → compatible', () => {
    const before = buildSchemaJson([])
    const after = buildSchemaJson([prop({ name: 'new', kind: 'string', required: false })])
    expect(diffSchemas(before, after).some((c) => c.severity === 'compatible' && c.reason.includes('new optional'))).toBe(true)
  })

  test('hasBreakingChanges детектит хотя бы одно breaking', () => {
    const before = buildSchemaJson([prop({ name: 'a', kind: 'string' })])
    const after = buildSchemaJson([])
    expect(hasBreakingChanges(diffSchemas(before, after))).toBe(true)
  })

  test('compatible-only changes: hasBreakingChanges=false', () => {
    const before = buildSchemaJson([])
    const after = buildSchemaJson([prop({ name: 'new', kind: 'string', required: false })])
    expect(hasBreakingChanges(diffSchemas(before, after))).toBe(false)
  })
})

describe('suggestVersionBump', () => {
  test('breaking → major bump', () => {
    expect(suggestVersionBump('1.2.3', [{ severity: 'breaking', field: 'a', reason: 'removed' }]))
      .toBe('2.0.0')
  })

  test('compatible-only → minor bump', () => {
    expect(suggestVersionBump('1.2.3', [{ severity: 'compatible', field: 'a', reason: 'added' }]))
      .toBe('1.3.0')
  })

  test('metadata-only → patch bump', () => {
    expect(suggestVersionBump('1.2.3', [{ severity: 'metadata', field: 'a', reason: 'description' }]))
      .toBe('1.2.4')
  })

  test('пустой changes → версия не меняется', () => {
    expect(suggestVersionBump('1.2.3', [])).toBe('1.2.3')
  })

  test('default 1.0.0 если current undefined', () => {
    expect(suggestVersionBump(undefined, [{ severity: 'breaking', field: 'x', reason: 'removed' }]))
      .toBe('2.0.0')
  })

  test('mix of breaking + compatible → major (breaking побеждает)', () => {
    expect(suggestVersionBump('1.0.0', [
      { severity: 'compatible', field: 'a', reason: 'added' },
      { severity: 'breaking', field: 'b', reason: 'removed' },
    ])).toBe('2.0.0')
  })
})
