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

// `blocks` is stored as a JSON string (MEDIUMTEXT) and parsed in the model.
const COLS = [
  'id', 'slug', 'title', 'blocks', 'status', 'protected', 'author_id',
  'seo_title', 'meta_description', 'og_image', 'canonical_url', 'robots',
  'layout', 'show_in_nav', 'nav_group', 'nav_order',
  'created_at', 'updated_at', 'published_at',
].join(', ')

// Admin list — every page, newest first. Excludes the (potentially large)
// blocks payload; callers that need it fetch the row by id/slug.
async function listSummaries() {
  return query(
    `SELECT id, slug, title, status, protected, show_in_nav, nav_group, nav_order,
            updated_at, published_at
     FROM pages ORDER BY updated_at DESC, id DESC`,
  )
}

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

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

// Insert a fully-formed column map. `blocks` must already be a JSON string.
async function insert(page) {
  const res = await query(
    `INSERT INTO pages
      (slug, title, blocks, status, protected, author_id,
       seo_title, meta_description, og_image, canonical_url, robots,
       layout, show_in_nav, nav_group, nav_order, published_at)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
    [
      page.slug,
      page.title,
      page.blocks,
      page.status,
      page.protected ? 1 : 0,
      page.author_id ?? null,
      page.seo_title ?? null,
      page.meta_description ?? null,
      page.og_image ?? null,
      page.canonical_url ?? null,
      page.robots ?? null,
      page.layout ?? 'default',
      page.show_in_nav ? 1 : 0,
      page.nav_group ?? null,
      page.nav_order ?? null,
      page.published_at ?? null,
    ],
  )
  return res.insertId
}

// Update only the provided columns. Keys must be real column names (the model
// builds this map from a whitelist, never straight from the request body).
async function update(id, fields) {
  const cols = []
  const params = []
  for (const [key, val] of Object.entries(fields)) {
    cols.push(`${key} = ?`)
    params.push(val)
  }
  if (cols.length === 0) return
  params.push(id)
  await query(`UPDATE pages SET ${cols.join(', ')} WHERE id = ?`, params)
}

async function remove(id) {
  return query('DELETE FROM pages WHERE id = ?', [id])
}

module.exports = { listSummaries, findById, findBySlug, insert, update, remove }
