<?php

/**
 * Migration 041 – Create redirects table
 *
 * Stores URL redirect rules (301/302) for SEO-friendly slug changes
 * and manual redirects managed via admin interface.
 */

use App\Database\Migration;

class CreateRedirects extends Migration
{
    public function up(): void
    {
        $this->db->query("
            CREATE TABLE IF NOT EXISTS iw_redirects (
                id              INT AUTO_INCREMENT PRIMARY KEY,
                source_path     VARCHAR(500)  NOT NULL COMMENT 'Source URL path (without domain)',
                target_url      VARCHAR(1000) NOT NULL COMMENT 'Target URL (path or full URL)',
                status_code     SMALLINT      NOT NULL DEFAULT 301 COMMENT '301 permanent or 302 temporary',
                hit_count       INT           NOT NULL DEFAULT 0,
                is_active       TINYINT(1)    NOT NULL DEFAULT 1,
                created_at      DATETIME      DEFAULT CURRENT_TIMESTAMP,
                updated_at      DATETIME      DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                UNIQUE INDEX idx_source_path (source_path(191)),
                INDEX idx_is_active (is_active)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        // Add redirect_manager_enabled setting
        $exists = $this->db->fetch(
            "SELECT 1 FROM iw_settings WHERE setting_key = 'redirect_manager_enabled'"
        );
        if (!$exists) {
            $this->db->insert('iw_settings', [
                'setting_key'   => 'redirect_manager_enabled',
                'setting_value' => '1',
                'setting_group' => 'features',
            ]);
        }
    }

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