/**
 * 統一 DB 介面：SQLite（開發）與 PostgreSQL（正式）共用。
 */
export type DbDialect = 'sqlite' | 'postgres'

export type GpLiveDbRunResult = {
    changes?: number
    lastID?: number
}

export interface GpLivePreparedStatement {
    run(...params: unknown[]): Promise<GpLiveDbRunResult>
    finalize(): Promise<void>
}

export interface GpLiveDb {
    readonly dialect: DbDialect
    run(sql: string, ...params: unknown[]): Promise<GpLiveDbRunResult>
    get<T = unknown>(sql: string, ...params: unknown[]): Promise<T | undefined>
    all<T = unknown>(sql: string, ...params: unknown[]): Promise<T[]>
    prepare(sql: string): Promise<GpLivePreparedStatement>
    exec(sql: string): Promise<void>
    close(): Promise<void>
}

export function isPostgresDb(db: GpLiveDb): db is GpLiveDb & { dialect: 'postgres' } {
    return db.dialect === 'postgres'
}

export function usePostgres(): boolean {
    const driver = process.env.GP_LIVE_DB_DRIVER?.trim().toLowerCase()
    if (driver === 'postgres' || driver === 'postgresql') return true
    if (driver === 'sqlite') return false
    return Boolean(process.env.DATABASE_URL?.trim())
}
