import pg from 'pg'

const DATABASE_URL = process.env.DATABASE_URL || 'postgres://postgres:postgres@localhost:5432/calctext'

const pool = new pg.Pool({ connectionString: DATABASE_URL })

/**
 * Fetch a Y.Doc snapshot from the database.
 * Returns the binary state or null if not found.
 */
export async function fetchDocument(documentId: string): Promise<Uint8Array | null> {
  try {
    const result = await pool.query(
      'SELECT state FROM ydoc_snapshots WHERE document_id = $1',
      [documentId],
    )

    if (result.rows.length === 0) return null

    const state = result.rows[0].state
    // state is stored as BYTEA in PostgreSQL, pg returns it as a Buffer
    if (Buffer.isBuffer(state)) {
      return new Uint8Array(state)
    }
    // If stored as integer array (from JSON), convert
    if (Array.isArray(state)) {
      return new Uint8Array(state)
    }

    return null
  } catch (error) {
    console.error('Failed to fetch document:', documentId, error)
    return null
  }
}

/**
 * Store a Y.Doc snapshot to the database.
 */
export async function storeDocument(documentId: string, state: Uint8Array): Promise<void> {
  try {
    await pool.query(
      `INSERT INTO ydoc_snapshots (document_id, state, updated_at)
       VALUES ($1, $2, NOW())
       ON CONFLICT (document_id) DO UPDATE SET state = $2, updated_at = NOW()`,
      [documentId, Buffer.from(state)],
    )
  } catch (error) {
    console.error('Failed to store document:', documentId, error)
  }
}
