import db from '../config/db.js';

const News = {
  async getAll() {
    const [rows] = await db.query('SELECT * FROM news_posts ORDER BY published_at DESC');
    return rows;
  },

  async getBySlug(slug) {
    const [rows] = await db.query('SELECT * FROM news_posts WHERE slug = ?', [slug]);
    return rows[0] || null;
  },

  async getById(id) {
    const [rows] = await db.query('SELECT * FROM news_posts WHERE id = ?', [id]);
    return rows[0] || null;
  },

  async create(data) {
    const { slug, title, excerpt, image, category, author, published_at, content, sort_order } = data;
    const [result] = await db.query(
      `INSERT INTO news_posts
        (slug, title, excerpt, image, category, author, published_at, content, sort_order)
       VALUES (?,?,?,?,?,?,?,?,?)`,
      [
        slug, title,
        excerpt || '', image || '',
        category || '', author || '32 MISSIONS Team',
        published_at || new Date().toISOString().slice(0, 10),
        JSON.stringify(content || []),
        sort_order || 0,
      ]
    );
    return result.insertId;
  },

  async update(id, data) {
    const { slug, title, excerpt, image, category, author, published_at, content, sort_order } = data;
    const [result] = await db.query(
      `UPDATE news_posts SET
        slug=?, title=?, excerpt=?, image=?, category=?,
        author=?, published_at=?, content=?, sort_order=?
       WHERE id=?`,
      [
        slug, title,
        excerpt || '', image || '',
        category || '', author || '32 MISSIONS Team',
        published_at || new Date().toISOString().slice(0, 10),
        JSON.stringify(content || []),
        sort_order || 0, id,
      ]
    );
    return result.affectedRows;
  },

  async remove(id) {
    const [result] = await db.query('DELETE FROM news_posts WHERE id = ?', [id]);
    return result.affectedRows;
  },
};

export default News;