<?php

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

return new class extends Migration {
    public function up(): void
    {
        if (!Schema::hasTable('telegraph_chats')) {
            return;
        }

        DB::statement("ALTER TABLE `telegraph_chats` MODIFY `chat_id` VARCHAR(32) NOT NULL");

        DB::statement(<<<SQL
            UPDATE `telegraph_chats`
            SET `chat_id` = TRIM(SUBSTRING(`name`, 6))
            WHERE `name` REGEXP '^Chat [0-9-]+'
        SQL);
    }

    public function down(): void
    {
        if (!Schema::hasTable('telegraph_chats')) {
            return;
        }

        DB::statement("ALTER TABLE `telegraph_chats` MODIFY `chat_id` BIGINT UNSIGNED NOT NULL");
    }
};
