import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { sql } from 'drizzle-orm'
import { text, pgTable } from 'drizzle-orm/pg-core'
import { createPgliteClient } from '../../db/src/postgres/pglite.js'
import { pushSchema } from './migrate.js'
import { makePgHarness } from './pg-harness.js'
import { i18nContentSchema, translationValue } from './schema.js'

const h = await makePgHarness()
beforeAll(async () => {
  await pushSchema(h.db)
  await h.db.execute(sql`
    insert into languages (code, is_active, is_default) values ('en', true, true)`)
})
afterAll(async () => {
  await h.teardown()
})

describe('i18n-content migrate', () => {
  it('pushSchema is idempotent (CREATE … IF NOT EXISTS) on a fresh and re-run DB', async () => {
    await expect(pushSchema(h.db)).resolves.toBeUndefined()
  })

  it('accepts a query handle typed over a merged schema', async () => {
    const catalogProbe = pgTable('catalog_probe', {
      id: text('id').primaryKey(),
    })
    const db = createPgliteClient({
      schema: {
        ...i18nContentSchema,
        catalogProbe,
      },
    })

    await expect(pushSchema(db)).resolves.toBeUndefined()
  })

  it('UNIQUE (entity_type, entity_id, field_key, locale) bites', async () => {
    await h.db.execute(sql`
      insert into translation_value (entity_type, entity_id, field_key, locale, value)
      values ('deal', 'd1', 'title', 'en', 'Hello')`)
    await expect(
      h.db.execute(sql`
        insert into translation_value (entity_type, entity_id, field_key, locale, value)
        values ('deal', 'd1', 'title', 'en', 'Duplicate')`),
    ).rejects.toThrow()
  })

  it('partial UNIQUE on languages.is_default WHERE is_default = true bites', async () => {
    await expect(
      h.db.execute(sql`
        insert into languages (code, is_active, is_default) values ('fr', true, true)`),
    ).rejects.toThrow()
  })

  it('allows inserting a value > 2704 bytes (btree-safety: partial index excludes long values)', async () => {
    const longValue = 'a'.repeat(3000)
    await expect(
      h.db.insert(translationValue).values({
        entityType: 'deal',
        entityId: 'test1',
        fieldKey: 'body_md',
        locale: 'en',
        value: longValue,
        sourceHash: '',
        status: 'OK',
        manualOverride: false,
      }),
    ).resolves.not.toThrow()
  })
})
