<?php

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

/**
 * Adds the columns needed to make the contact custom-fields feature
 * match what the docs (Documentation/pages/features/contacts-crm.html)
 * have been advertising for v1.x:
 *
 *   - placeholder    Greyed-out hint inside the input. Docs explicitly
 *                    listed "placeholder text" as a configuration option.
 *   - default_value  Pre-filled on new contacts. Docs called this out
 *                    as a per-field configuration option.
 *   - group_name     Collapsible group label on the contact detail page
 *                    (e.g. "Subscription Details", "Preferences").
 *                    Docs called this "Field Groups".
 *   - group_order    Display order within a group. sort_order continues
 *                    to be the absolute order across the whole form when
 *                    the admin doesn't use groups.
 *
 * Also relaxes the `type` ENUM into a varchar so we can add multi_select
 * and long_text (also advertised) without another ALTER ENUM dance the
 * next time we extend the field type set. The migration accepts both
 * MySQL (where the ENUM exists) and SQLite (where it never existed in
 * the first place) — see down() for the rollback shape.
 */
return new class extends Migration
{
    public function up(): void
    {
        $driver = Schema::getConnection()->getDriverName();

        if ($driver === 'mysql' || $driver === 'mariadb') {
            // Relax the ENUM so multi_select / long_text (and any future
            // type) work without another migration. Hard-coded ALTER
            // because doctrine/dbal doesn't ship with Laravel 11+ and
            // the lighter alternative would be dropping + recreating
            // the column, which would wipe existing rows.
            DB::statement("ALTER TABLE custom_fields MODIFY type VARCHAR(32) NOT NULL DEFAULT 'text'");
        }
        // SQLite ignored — its original column type was inferred and it
        // doesn't enforce ENUM constraints, so the existing column
        // already accepts any string.

        Schema::table('custom_fields', function (Blueprint $table) {
            $table->string('placeholder')->nullable()->after('options');
            $table->text('default_value')->nullable()->after('placeholder');
            $table->string('group_name')->nullable()->after('default_value');
            $table->unsignedInteger('group_order')->default(0)->after('group_name');

            $table->index(['workspace_id', 'group_name']);
        });
    }

    public function down(): void
    {
        Schema::table('custom_fields', function (Blueprint $table) {
            $table->dropIndex(['workspace_id', 'group_name']);
            $table->dropColumn(['placeholder', 'default_value', 'group_name', 'group_order']);
        });

        $driver = Schema::getConnection()->getDriverName();
        if ($driver === 'mysql' || $driver === 'mariadb') {
            // Restore the ENUM only after dropping any rows that would
            // violate it — otherwise the ALTER fails on the first
            // multi_select / long_text row.
            DB::table('custom_fields')
                ->whereNotIn('type', ['text', 'number', 'date', 'dropdown', 'checkbox', 'url', 'email', 'phone'])
                ->delete();
            DB::statement("ALTER TABLE custom_fields MODIFY type ENUM('text', 'number', 'date', 'dropdown', 'checkbox', 'url', 'email', 'phone') NOT NULL DEFAULT 'text'");
        }
    }
};
