<?php

/**
 * Migration 039 – Create content revisions table
 *
 * Stores version history for pages and blog posts.
 * Limited to 10 revisions per item (FIFO cleanup in model).
 * Also adds the content_revisions_enabled setting.
 */

use App\Database\Migration;

class CreateContentRevisions extends Migration
{
    public function up(): void
    {
        $this->db->query("
            CREATE TABLE IF NOT EXISTS iw_content_revisions (
                id              INT AUTO_INCREMENT PRIMARY KEY,
                content_type    VARCHAR(50)  NOT NULL COMMENT 'page or blog_post',
                content_id      INT          NOT NULL,
                title           VARCHAR(500) DEFAULT NULL,
                snapshot        LONGTEXT     NOT NULL COMMENT 'JSON snapshot of all fields',
                changed_by      INT          DEFAULT NULL,
                created_at      DATETIME     DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_content (content_type, content_id),
                INDEX idx_created (content_type, content_id, created_at),
                CONSTRAINT fk_content_rev_user FOREIGN KEY (changed_by) REFERENCES iw_users(id) ON DELETE SET NULL
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        // Setting
        $existing = $this->db->fetch(
            "SELECT id FROM iw_settings WHERE setting_key = 'content_revisions_enabled' LIMIT 1"
        );
        if (!$existing) {
            $this->db->insert('iw_settings', [
                'setting_key'   => 'content_revisions_enabled',
                'setting_value' => '1',
                'setting_group' => 'general',
            ]);
        }
    }

    public function down(): void
    {
        $this->db->query("DROP TABLE IF EXISTS iw_content_revisions");
        $this->db->query("DELETE FROM iw_settings WHERE setting_key = 'content_revisions_enabled'");
    }
}
