import pg from 'pg'

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

export async function initDb() {
  await pool.query(`
    CREATE TABLE IF NOT EXISTS hk_config (
      key   TEXT PRIMARY KEY,
      value JSONB NOT NULL DEFAULT 'null'::jsonb
    )
  `)
  await pool.query(`
    CREATE TABLE IF NOT EXISTS workforce_daily_shifts (
      date      TEXT PRIMARY KEY,
      synced_at TIMESTAMPTZ NOT NULL DEFAULT now(),
      source    TEXT NOT NULL DEFAULT 'workforce',
      staff     JSONB NOT NULL DEFAULT '[]'::jsonb
    )
  `)
}

export async function getConfig(key, defaultVal = null) {
  const { rows } = await pool.query('SELECT value FROM hk_config WHERE key = $1', [key])
  return rows.length ? rows[0].value : defaultVal
}

export async function setConfig(key, value) {
  await pool.query(
    `INSERT INTO hk_config (key, value) VALUES ($1, $2::jsonb)
     ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,
    [key, JSON.stringify(value)]
  )
}

export async function getWorkforceShifts(start, end) {
  const { rows } = await pool.query(
    `SELECT date, synced_at, source, staff FROM workforce_daily_shifts
     WHERE date >= $1 AND date <= $2 ORDER BY date`,
    [start, end]
  )
  const result = {}
  for (const row of rows) {
    result[row.date] = { synced_at: row.synced_at, source: row.source, staff: row.staff }
  }
  return result
}

export async function upsertWorkforceShifts(dailyRows) {
  if (!dailyRows.length) return
  const client = await pool.connect()
  try {
    await client.query('BEGIN')
    for (const row of dailyRows) {
      await client.query(
        `INSERT INTO workforce_daily_shifts (date, synced_at, source, staff)
         VALUES ($1, now(), 'workforce', $2::jsonb)
         ON CONFLICT (date) DO UPDATE SET synced_at = now(), staff = EXCLUDED.staff`,
        [row.date, JSON.stringify(row.staff)]
      )
    }
    await client.query('COMMIT')
  } catch (err) {
    await client.query('ROLLBACK')
    throw err
  } finally {
    client.release()
  }
}
