-- =========================================================
-- MIGRASI: Penanda PERSISTEN Hasil Apply Struktur Otomatis
-- =========================================================
-- Tujuan:
--   Menambahkan kolom penanda pada tabel `sections` agar section
--   yang dibuat oleh proses "Terapkan Struktur Disetujui"
--   (Struktur Kitab Otomatis) dapat dikenali SECARA PERSISTEN,
--   bahkan setelah draft (kitab_struktur_drafts) dihapus oleh
--   "Reset Struktur".
--
--   Dengan penanda ini, fitur "Hapus Hasil Apply" tetap dapat
--   menemukan & menghapus HANYA section hasil Apply, tanpa
--   menyentuh section lama/manual maupun chapter nyata.
--
-- KEAMANAN:
--   - Kolom bersifat NULL-able. Section lama/manual tetap NULL
--     sehingga TIDAK PERNAH ikut terhapus.
--   - Tidak ada DELETE/UPDATE data lama di migrasi ini.
--   - Idempotent: aman dijalankan berulang (dicek via information_schema).
--
-- Jalankan SEKALI di hosting (phpMyAdmin / CLI):
--   mysql -u USER -p NAMA_DB < database/migration_apply_source_sections.sql
-- =========================================================

SET @dbname = DATABASE();

-- 1. Tambah kolom `apply_source` bila belum ada.
SET @col_exists = (
    SELECT COUNT(*)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = @dbname
      AND TABLE_NAME   = 'sections'
      AND COLUMN_NAME  = 'apply_source'
);

SET @sql_add_col = IF(
    @col_exists = 0,
    'ALTER TABLE `sections`
        ADD COLUMN `apply_source` VARCHAR(32) NULL DEFAULT NULL
        COMMENT ''Penanda hasil Apply Struktur Otomatis (mis. struktur-otomatis). NULL = section lama/manual''',
    'SELECT ''Kolom apply_source sudah ada — dilewati'' AS info'
);

PREPARE stmt_add_col FROM @sql_add_col;
EXECUTE stmt_add_col;
DEALLOCATE PREPARE stmt_add_col;

-- 2. Tambah index `idx_sections_apply_source` bila belum ada.
SET @idx_exists = (
    SELECT COUNT(*)
    FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = @dbname
      AND TABLE_NAME   = 'sections'
      AND INDEX_NAME   = 'idx_sections_apply_source'
);

SET @sql_add_idx = IF(
    @idx_exists = 0,
    'ALTER TABLE `sections` ADD INDEX `idx_sections_apply_source` (`apply_source`)',
    'SELECT ''Index idx_sections_apply_source sudah ada — dilewati'' AS info'
);

PREPARE stmt_add_idx FROM @sql_add_idx;
EXECUTE stmt_add_idx;
DEALLOCATE PREPARE stmt_add_idx;

-- =========================================================
-- SELESAI. Setelah migrasi:
--   - Section hasil Apply BARU otomatis ditandai apply_source='struktur-otomatis'.
--   - Section lama/manual tetap apply_source = NULL (aman).
--   - Untuk data lama book_id=23, gunakan fitur "Pulihkan Penanda Apply"
--     (lihat admin/struktur) atau jalankan recovery satu kali dari UI.
-- =========================================================
