const { query } = require('../../utils/db')

const COLS =
  'id, kind, name, enabled, client_id, client_secret_enc, authorize_url, token_url, userinfo_url, scopes, priority, created_at, updated_at'

async function list() {
  return query(`SELECT ${COLS} FROM auth_providers ORDER BY priority ASC, id ASC`)
}

async function get(id) {
  const rows = await query(`SELECT ${COLS} FROM auth_providers WHERE id = ? LIMIT 1`, [id])
  return rows[0] || null
}

// Upsert a provider row. `fields` are column values already prepared by the model
// (secret pre-encrypted). Only the provided columns are written/updated.
async function upsert(id, fields) {
  const cols = Object.keys(fields)
  const vals = cols.map((c) => fields[c])
  const insertCols = ['id', ...cols].map((c) => `\`${c}\``).join(', ')
  const placeholders = ['?', ...cols.map(() => '?')].join(', ')
  const updates = cols.map((c) => `\`${c}\` = VALUES(\`${c}\`)`).join(', ')
  await query(
    `INSERT INTO auth_providers (${insertCols}) VALUES (${placeholders})
     ON DUPLICATE KEY UPDATE ${updates}`,
    [id, ...vals],
  )
  return get(id)
}

async function remove(id) {
  const res = await query('DELETE FROM auth_providers WHERE id = ?', [id])
  return Number(res.affectedRows || 0)
}

module.exports = { list, get, upsert, remove }
