import type { SQLWrapper } from 'drizzle-orm'
import { getTransactionIdentity } from './index.js'
import type {
  Database,
  PostgresTransaction,
  Querier,
  Transaction,
  TransactionIdentity,
  TransactionalDatabase,
} from './index.js'

type AssertFalse<T extends false> = T
type S = Record<string, unknown>

declare const db: Database<S>
declare const txDb: TransactionalDatabase<S>
declare const pgTx: PostgresTransaction<S>

type DatabaseHasTransaction = 'transaction' extends keyof Database<S> ? true : false
type DatabaseIsTransaction = Database<S> extends Transaction<S> ? true : false
export type _DatabaseHasNoTransaction = AssertFalse<DatabaseHasTransaction>
export type _DatabaseHasNoCapability = AssertFalse<DatabaseIsTransaction>

void txDb.transaction(async (innerTx) => {
  const q: Querier<S> = innerTx
  void q
})

const fromDb: Querier<S> = db
const fromTx: Querier<S> = pgTx
void fromDb
void fromTx

interface ForeignPackageTransaction<T> {
  readonly $platformTransaction: { readonly schema: T }
  execute<Row extends Record<string, unknown> = Record<string, unknown>>(
    query: SQLWrapper,
  ): Promise<readonly Row[]>
}

interface ForeignPackageTransactionIdentity {
  readonly $platformTransactionIdentity: 'v1'
}

type ContentSchema = { content: unknown }
type FieldsSchema = { fields: unknown }
type CombinedSchema = ContentSchema & FieldsSchema

declare const combinedTx: Transaction<CombinedSchema>
declare const query: SQLWrapper
declare const foreignTx: ForeignPackageTransaction<CombinedSchema>
declare const foreignIdentity: ForeignPackageTransactionIdentity
const contentTx: Transaction<ContentSchema> = combinedTx
const fieldsTx: Transaction<FieldsSchema> = combinedTx
const duplicateCopyCompatible: Transaction<CombinedSchema> = foreignTx
const duplicateIdentityCompatible: TransactionIdentity = foreignIdentity
const rows: Promise<readonly { id: string }[]> = combinedTx.execute<{ id: string }>(query)
const identity: TransactionIdentity = getTransactionIdentity(combinedTx)
void contentTx
void fieldsTx
void duplicateCopyCompatible
void duplicateIdentityCompatible
void rows
void identity
