/**
 * OAuth authorization code storage — S10-005 regression.
 */
import { describe, it, expect, vi } from 'vitest'

describe('insertAuthorizationCode (S10-005)', () => {
  it('persists the hashed code, not plaintext', async () => {
    const codeHash = 'sha256-hash-of-plaintext-code'
    const insertedRows: Record<string, unknown>[] = []

    const db = {
      transaction: vi.fn(async (fn: (tx: unknown) => Promise<void>) => {
        const tx = {
          insert: vi.fn(() => ({
            values: vi.fn((values: Record<string, unknown>) => {
              insertedRows.push(values)
              return Promise.resolve()
            }),
          })),
        }
        await fn(tx)
      }),
    }

    const { insertAuthorizationCode } = await import('../../src/queries/oauth')
    await insertAuthorizationCode(db as never, {
      code: codeHash,
      oauthClientId: 'client-id',
      tenantId: 'tenant-id',
      userId: 'user-id',
      redirectUri: 'https://example.com/cb',
      scope: 'read:customers',
      codeChallenge: 'challenge',
      codeChallengeMethod: 'S256',
      expiresAt: new Date(),
    })

    expect(insertedRows[0]?.code).toBe(codeHash)
  })
})

describe('lookupAuthorizationCode (S10-005)', () => {
  it('queries by the hash passed from the caller', async () => {
    const codeHash = 'sha256-hash-of-plaintext-code'

    const db = {
      select: vi.fn(() => ({
        from: vi.fn(() => ({
          where: vi.fn(() => ({
            limit: vi.fn(() => Promise.resolve([])),
          })),
        })),
      })),
    }

    const { lookupAuthorizationCode } = await import('../../src/queries/oauth')
    const row = await lookupAuthorizationCode(db as never, codeHash)

    expect(row).toBeNull()
    expect(db.select).toHaveBeenCalledOnce()
  })
})
