import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { sql } from 'drizzle-orm'
import { makePgHarness } from './pg-harness.js'
import { fieldsMigrationSql } from './migrate.js'

const h = await makePgHarness()
beforeAll(async () => {
  for (const s of fieldsMigrationSql()
    .split(';')
    .map((x) => x.trim())
    .filter(Boolean)) {
    await h.db.execute(sql.raw(s))
  }
})
afterAll(async () => { await h.teardown() })

describe('schema migration', () => {
  it('creates field_values + field_groups', async () => {
    const r = (await h.db.execute(sql`select table_name from information_schema.tables where table_name in ('field_values','field_groups')`)) as { rows: unknown[] }
    expect(r.rows.length).toBe(2)
  })
  it('CHECK rejects a row with two value lanes set', async () => {
    await expect(h.db.execute(sql`
      insert into field_values (entity_type, entity_id, group_id, field_key, value_text, value_num)
      values ('product','p1','attrs','material','leather', 10)`)).rejects.toThrow()
  })
  it('UNIQUE (entity_type,entity_id,group_id,field_key,ordinal) bites', async () => {
    await h.db.execute(sql`insert into field_values (entity_type,entity_id,group_id,field_key,value_text) values ('product','p2','attrs','material','leather')`)
    await expect(h.db.execute(sql`insert into field_values (entity_type,entity_id,group_id,field_key,value_text) values ('product','p2','attrs','material','suede')`)).rejects.toThrow()
  })
})
