import { sql } from 'drizzle-orm'
import { describe, it } from 'vitest'
import { createPgliteClient } from '@platform-modules/db/pglite'
import { runRecordStoreConformance } from '../conformance.js'
import type { RecordStore } from '../types.js'
import { makeQuerierRecordStore } from './index.js'
import { recordStoreSchema, recordStoreTable } from './table.js'

const CREATE_RECORD_STORE_TABLE = sql`
  CREATE TABLE record_store (
    seq bigserial PRIMARY KEY,
    id text NOT NULL,
    created_at_ms bigint NOT NULL,
    record jsonb NOT NULL
  )
`

const CREATE_RECORD_STORE_INDEX = sql`
  CREATE INDEX record_store_created_at_ms_seq_idx ON record_store (created_at_ms DESC, seq DESC)
`

const TRUNCATE_RECORD_STORE = sql`TRUNCATE record_store RESTART IDENTITY`

type JsonRecord = Record<string, unknown>

type TestDb = ReturnType<typeof createPgliteClient<typeof recordStoreSchema>>

let sharedDb: TestDb | undefined

async function getTestDb(): Promise<TestDb> {
  if (sharedDb === undefined) {
    sharedDb = createPgliteClient({ schema: recordStoreSchema })
    await sharedDb.execute(CREATE_RECORD_STORE_TABLE)
    await sharedDb.execute(CREATE_RECORD_STORE_INDEX)
  }
  return sharedDb
}

async function setupStore(opts?: {
  now?: () => string
  makeId?: () => string
}): Promise<RecordStore<JsonRecord>> {
  const db = await getTestDb()
  await db.execute(TRUNCATE_RECORD_STORE)
  return makeQuerierRecordStore<JsonRecord, typeof recordStoreSchema>(
    db,
    recordStoreTable,
    opts,
  )
}

describe('makeQuerierRecordStore', () => {
  it('conforms', async () => {
    await runRecordStoreConformance((opts) => setupStore(opts))
  }, 30_000)
})
