<?php

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

/**
 * Extend the `channel` column on ai_channel_configs to accept 'slack'.
 *
 * Background: the original v1.1 migration defined `channel` as a MySQL
 * ENUM locked to email/whatsapp/sms/live_chat/telegram. Slack inbound +
 * AI reply send paths were already wired (AutoReplyListener,
 * GenerateAIReplyJob, SendAIReplyJob::deliverSlack), but admins couldn't
 * save a per-channel config row for Slack because the DB would reject
 * the value at write time.
 *
 * Strategy: convert the column from ENUM → VARCHAR(32). This matches what
 * v1.4 already did for conversations.channel — the platform's pattern
 * for channel columns going forward, so adding the next channel (e.g.
 * Instagram via the addon system) is a one-line model change instead of
 * another schema migration.
 *
 * Safe to run on existing installs: rows keep their values; only the
 * column type changes.
 */
return new class extends Migration {
    public function up(): void
    {
        // Use a raw statement because the DBAL doctrine/dbal package can't
        // diff an ENUM → VARCHAR change on MySQL via Schema::table().
        // Skip on non-MySQL drivers (SQLite test envs treat the original
        // enum as TEXT already so there's nothing to change).
        if (! Schema::hasTable('ai_channel_configs')) {
            return;
        }

        $driver = DB::connection()->getDriverName();
        if ($driver === 'mysql' || $driver === 'mariadb') {
            DB::statement('ALTER TABLE ai_channel_configs MODIFY COLUMN channel VARCHAR(32) NOT NULL');
        }
    }

    public function down(): void
    {
        // Best-effort revert: drop any Slack rows first (they would
        // violate the narrower enum) then shrink back to the original
        // ENUM definition.
        if (! Schema::hasTable('ai_channel_configs')) {
            return;
        }

        DB::table('ai_channel_configs')->where('channel', 'slack')->delete();

        $driver = DB::connection()->getDriverName();
        if ($driver === 'mysql' || $driver === 'mariadb') {
            DB::statement("ALTER TABLE ai_channel_configs MODIFY COLUMN channel ENUM('email','whatsapp','sms','live_chat','telegram') NOT NULL");
        }
    }
};
