<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * One `channel` column instead of a second CMS.
 *
 * The original plan had a whole workstream for "Mobile App Content": new
 * app_screens and app_blocks tables, a MobileBlockRegistry, mobile block
 * classes, an editor. But website_sections, website_news, website_menus, media,
 * the page builder and `website:blueprint export|import` all already exist and
 * already do that job — a parallel CMS would be a second migration surface, a
 * second editor to keep in step, and a second place for content to go missing,
 * forever.
 *
 * So: the portal reads the same tables the public site does, and this column
 * decides where an item appears. `both` is the default, because every piece of
 * content that exists today was written for an audience that now includes the
 * app.
 */
return new class extends Migration
{
    private const TABLES = ['website_news', 'website_sections'];

    public function up(): void
    {
        foreach (self::TABLES as $table) {
            if (! Schema::hasTable($table) || Schema::hasColumn($table, 'channel')) {
                continue;
            }

            Schema::table($table, function (Blueprint $t) {
                $t->string('channel', 10)->default('both')->after('academy_id');
            });

            if (DB::getDriverName() === 'pgsql') {
                DB::statement("ALTER TABLE {$table} ADD CONSTRAINT {$table}_channel_check CHECK (channel IN ('website','app','both'))");
            }

            Schema::table($table, function (Blueprint $t) use ($table) {
                $t->index(['academy_id', 'channel'], "{$table}_academy_channel_index");
            });
        }
    }

    public function down(): void
    {
        foreach (self::TABLES as $table) {
            if (Schema::hasTable($table) && Schema::hasColumn($table, 'channel')) {
                if (DB::getDriverName() === 'pgsql') {
                    DB::statement("ALTER TABLE {$table} DROP CONSTRAINT IF EXISTS {$table}_channel_check");
                }

                Schema::table($table, function (Blueprint $t) {
                    $t->dropColumn('channel');
                });
            }
        }
    }
};
