import { describe, expect, it } from 'bun:test'
import {
  foreignKeyCode,
  generateSequencesFunction,
  indexCode,
  modifiedColumns,
  namedForeignKey,
  postgresIdentifier,
  sequenceCode,
  sqlTemplate,
} from './schemaCode'

/** What a `sql\`...\`` template written as `source` reads back as. */
const cooked = (source: string): string => {
  const tag = (strings: TemplateStringsArray) => strings[0] ?? ''
  return new Function('tag', `return tag${source.replace(/^sql/, '')}`)(tag)
}

describe('postgresIdentifier', () => {
  it('leaves a name of 63 bytes or fewer alone', () => {
    const name = 'a'.repeat(63)
    expect(postgresIdentifier(name)).toBe(name)
  })

  it('cuts a longer name to 63 bytes, as Postgres does', () => {
    const name = 'commerce_price_list_assignments_price_list_id_commerce_price_lists_id_fk'
    expect(name.length).toBeGreaterThan(63)
    expect(postgresIdentifier(name)).toBe(name.slice(0, 63))
  })

  it('never splits a multi-byte character', () => {
    const cut = postgresIdentifier(`${'a'.repeat(62)}ü`)
    expect(cut).toBe('a'.repeat(62))
    expect(new TextEncoder().encode(cut).length).toBeLessThanOrEqual(63)
  })
})

describe('sqlTemplate', () => {
  it("keeps `$'` and `$&` as written (they are replacement patterns, not SQL)", () => {
    for (const text of ["col ~ '^[a-z]+$'", 'a $& b', "x $` y $' z"]) {
      expect(cooked(sqlTemplate(text))).toBe(text)
    }
  })

  it('keeps a backslash, a backtick and a template placeholder', () => {
    for (const text of [
      String.raw`code ~ '^\d+$'`,
      'name <> `x`',
      `label <> '$${'{'}not_a_placeholder}'`,
    ]) {
      expect(cooked(sqlTemplate(text))).toBe(text)
    }
  })
})

describe('indexCode', () => {
  it('writes order, nulls position and operator class on the column', () => {
    const code = indexCode('invoices', {
      name: 'invoice_issue_index',
      columns: ['org_id', 'issue_date'],
      columnOptions: { issue_date: { order: 'desc', nulls: 'first' } },
    })
    expect(code).toBe("index('invoice_issue_index').on(t.orgId, t.issueDate.desc().nullsFirst())")
    const gin = indexCode('items', {
      name: 'items_attributes_gin',
      columns: ['attributes'],
      using: 'gin',
      columnOptions: { attributes: { opclass: 'jsonb_path_ops' } },
    })
    expect(gin).toBe(
      "index('items_attributes_gin').using('gin', t.attributes.op('jsonb_path_ops'))"
    )
  })

  it('writes asc and nulls last', () => {
    const code = indexCode('t', {
      name: 'i',
      columns: ['a'],
      columnOptions: { a: { order: 'asc', nulls: 'last' } },
    })
    expect(code).toContain('t.a.asc().nullsLast()')
  })

  it('cuts an index name over 63 bytes', () => {
    const name = `${'x'.repeat(70)}_index`
    expect(indexCode('t', { name, columns: ['a'] })).toBe(`index('${'x'.repeat(63)}').on(t.a)`)
  })

  it('reports which columns need the ExtraConfigColumn type', () => {
    const modified = modifiedColumns([
      { columns: ['a', 'b'], columnOptions: { b: { order: 'desc' }, a: {} } },
      { columns: ['c'] },
    ])
    expect([...modified]).toEqual(['b'])
  })
})

describe('namedForeignKey', () => {
  it("needs no name when drizzle's own is short enough", () => {
    expect(namedForeignKey('orders', 'user_id', { table: 'users', column: 'id' })).toBeUndefined()
  })

  it('names a key whose generated name drizzle-kit would see cut', () => {
    const name = namedForeignKey('commerce_price_list_assignments', 'organization_id', {
      table: 'partner_organizations',
      column: 'id',
    })
    expect(name).toBe('commerce_price_list_assignments_organization_id_partner_organiz')
    expect(name?.length).toBe(63)
  })

  it('uses the name a migration chose', () => {
    expect(namedForeignKey('t', 'c', { table: 'u', constraintName: 'chosen_fk' })).toBe('chosen_fk')
  })

  it('writes the key with its owner, target column and actions', () => {
    expect(
      foreignKeyCode('chosen_fk', 'typeVersionId', 'partnerRequestTypeRevisionsTable', {
        table: 'partner_request_type_revisions',
        column: 'version_id',
        onDelete: 'restrict',
      })
    ).toBe(
      "foreignKey({ name: 'chosen_fk', columns: [t.typeVersionId], foreignColumns: [partnerRequestTypeRevisionsTable.versionId] }).onDelete('restrict')"
    )
  })
})

describe('sequences', () => {
  it("writes Postgres' defaults for a bare name", () => {
    expect(sequenceCode({ name: 'order_number_seq' })).toBe(
      "schema.sequence('order_number_seq', { increment: 1, minValue: '1', maxValue: '9223372036854775807', startWith: '1', cache: 1, cycle: false })"
    )
  })

  it('carries every option', () => {
    const code = sequenceCode({
      name: 's',
      startWith: 1000,
      increment: 5,
      minValue: 1000,
      maxValue: 99999,
      cache: 10,
      cycle: true,
    })
    expect(code).toBe(
      "schema.sequence('s', { increment: 5, minValue: 1000, maxValue: 99999, startWith: 1000, cache: 10, cycle: true })"
    )
  })

  it('keys each sequence by its camelCase name', () => {
    const code = generateSequencesFunction([{ name: 'a_b_seq' }, { name: 'c_seq' }])
    expect(code).toContain(
      'export function createAllSequencesForSchema(schema: ReturnType<typeof pgSchema>)'
    )
    expect(code).toContain("aBSeq: schema.sequence('a_b_seq'")
    expect(code).toContain("cSeq: schema.sequence('c_seq'")
  })

  it('emits an empty function when nothing is declared', () => {
    expect(generateSequencesFunction([])).toContain('return {\n\t};')
  })

  it('refuses a duplicate name', () => {
    expect(() => generateSequencesFunction([{ name: 's' }, { name: 's' }])).toThrow(
      'declared twice'
    )
  })

  it('refuses a name Postgres would cut, because the push would recreate it at 1', () => {
    expect(() => generateSequencesFunction([{ name: 's'.repeat(64) }])).toThrow('longer than 63')
  })
})
