import assert from 'node:assert/strict'
import test from 'node:test'
import { Pool } from 'pg'

const connectionString = process.env.TEST_POSTGRES_URL

test('real PostgreSQL transaction rolls back atomically', { skip: !connectionString }, async () => {
  const pool = new Pool({ connectionString })
  const client = await pool.connect()
  const tableName = `integration_tx_${Date.now()}`
  try {
    await client.query(`CREATE TEMP TABLE ${tableName} (id integer primary key, value text)`)
    await client.query('BEGIN')
    await client.query(`INSERT INTO ${tableName} (id, value) VALUES (1, 'before-error')`)
    try {
      await client.query(`INSERT INTO ${tableName} (id, value) VALUES (1, 'duplicate')`)
    } catch {
      await client.query('ROLLBACK')
    }
    const result = await client.query(`SELECT COUNT(*)::int AS count FROM ${tableName}`)
    assert.equal(result.rows[0].count, 0)
  } finally {
    client.release()
    await pool.end()
  }
})

test(
  'real PostgreSQL enforces callback replay idempotency under concurrency',
  {
    skip: !connectionString,
  },
  async () => {
    const pool = new Pool({ connectionString })
    const tableName = `integration_webhook_${Date.now()}`
    try {
      await pool.query(
        `CREATE TABLE ${tableName} (
        id serial primary key,
        provider text not null,
        event_id text not null,
        unique(provider, event_id)
      )`,
      )
      await Promise.all(
        Array.from({ length: 8 }, () =>
          pool.query(
            `INSERT INTO ${tableName} (provider, event_id)
           VALUES ('integration', 'replay-1')
           ON CONFLICT (provider, event_id) DO NOTHING`,
          ),
        ),
      )
      const result = await pool.query(`SELECT COUNT(*)::int AS count FROM ${tableName}`)
      assert.equal(result.rows[0].count, 1)
    } finally {
      await pool.query(`DROP TABLE IF EXISTS ${tableName}`)
      await pool.end()
    }
  },
)
