const db = require('../../database/database')

exports.list = async () => {
  const [rows] = await db.query('SELECT * FROM news ORDER BY published_at DESC, created_at DESC')
  return rows
}

exports.get = async (idOrSlug) => {
  const [rows] = await db.query('SELECT * FROM news WHERE id = ? OR slug = ? LIMIT 1', [idOrSlug, idOrSlug])
  return rows?.[0] || null
}

exports.create = async (payload) => {
  const {
    title,
    summary,
    content,
    slug,
    category,
    object_storage_id,
    original_filename,
    is_active = 1,
    published_at = null,
  } = payload
  const [res] = await db.query(
    'INSERT INTO news (title, summary, content, slug, category, object_storage_id, original_filename, is_active, published_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
    [title, summary, content, slug, category, object_storage_id, original_filename, is_active, published_at]
  )
  return res.insertId
}

exports.update = async (id, payload) => {
  const fields = []
  const values = []
  const allowed = ['title','summary','content','slug','category','object_storage_id','original_filename','is_active','published_at']
  for (const key of allowed) {
    if (payload[key] !== undefined) {
      fields.push(`${key} = ?`)
      values.push(payload[key])
    }
  }
  if (!fields.length) return 0
  values.push(id)
  const [res] = await db.query(`UPDATE news SET ${fields.join(', ')} WHERE id = ?`, values)
  return res.affectedRows
}

exports.delete = async (id) => {
  const [res] = await db.query('DELETE FROM news WHERE id = ?', [id])
  return res.affectedRows
}
