/**
 * Uzupełnia schemat stagingu importów na produkcji (jednorazowe ALTER-y).
 */
import type { RowDataPacket } from 'mysql2'
import { getPool } from '@/lib/db'

async function columnExists(table: string, column: string): Promise<boolean> {
  const pool = getPool()
  const [rows] = await pool.execute<RowDataPacket[]>(
    `SELECT COUNT(*) AS c
     FROM information_schema.COLUMNS
     WHERE TABLE_SCHEMA = DATABASE()
       AND TABLE_NAME = ?
       AND COLUMN_NAME = ?`,
    [table, column],
  )
  return Number(rows[0]?.c ?? 0) > 0
}

/** Dodaje brakujące kolumny w `listing_imports` (np. offer_type na starszej bazie). */
export async function ensureListingImportsSchema(): Promise<void> {
  if (!process.env.DATABASE_URL?.trim()) return

  const pool = getPool()

  if (!(await columnExists('listing_imports', 'offer_type'))) {
    await pool.execute(
      `ALTER TABLE listing_imports
       ADD COLUMN offer_type VARCHAR(20) NOT NULL DEFAULT 'fixed'
         COMMENT 'fixed|negotiable|on_request'
       AFTER price_on_request`,
    )
  }
}
