import { sql } from 'drizzle-orm'
import { integer, pgTable, text } from 'drizzle-orm/pg-core'
import { it, expect } from 'vitest'
import { createPgliteClient } from './pglite.js'

const users = pgTable('users', {
  id: integer('id').primaryKey().generatedAlwaysAsIdentity(),
  name: text('name').notNull(),
})

const schema = { users }

it('round-trips insert and relational query typed from schema', async () => {
  const db = createPgliteClient({ schema })

  await db.execute(
    sql`CREATE TABLE users (id integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY, name text NOT NULL)`,
  )

  await db.insert(users).values({ name: 'alice' })

  const rows = await db.query.users.findMany()
  expect(rows).toEqual([{ id: 1, name: 'alice' }])
})

it('rolls back when .transaction() callback throws', async () => {
  const db = createPgliteClient({ schema })

  await db.execute(
    sql`CREATE TABLE users (id integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY, name text NOT NULL)`,
  )

  await expect(
    db.transaction(async (tx) => {
      await tx.insert(users).values({ name: 'rollback-me' })
      throw new Error('rollback')
    }),
  ).rejects.toThrow('rollback')

  const rows = await db.query.users.findMany()
  expect(rows).toHaveLength(0)
})
