<?php

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

/**
 * Strip stray leading/trailing whitespace — including the non-breaking space
 * U+00A0 that survives a copy-paste out of Word or a browser — from the names
 * users actually see.
 *
 * These characters are invisible in the admin forms but render as a gap in
 * page titles, receipts and the mobile app, and they break exact-match
 * lookups and sorting.
 *
 * Safe to re-run: trimming an already-trimmed value is a no-op.
 */
return new class extends Migration
{
    private const TARGETS = [
        'academies' => ['name', 'name_ar'],
        'branches' => ['name', 'name_ar'],
        'training_programs' => ['name', 'name_ar'],
        'training_groups' => ['name', 'name_ar'],
        'people' => ['name', 'name_ar'],
        'products' => ['name', 'name_ar'],
        'facilities' => ['name', 'name_ar'],
    ];

    public function up(): void
    {
        // E'...' is Postgres-specific; this project is Postgres-only, but guard
        // anyway so a non-pgsql connection cannot fail the whole deploy.
        if (DB::connection()->getDriverName() !== 'pgsql') {
            return;
        }

        foreach (self::TARGETS as $table => $columns) {
            if (! Schema::hasTable($table)) {
                continue;
            }

            foreach ($columns as $column) {
                if (! Schema::hasColumn($table, $column)) {
                    continue;
                }

                DB::statement(
                    "UPDATE {$table}
                     SET {$column} = btrim({$column}, E' \\u00a0\\t\\n\\r')
                     WHERE {$column} IS NOT NULL
                       AND {$column} <> btrim({$column}, E' \\u00a0\\t\\n\\r')"
                );
            }
        }
    }

    public function down(): void
    {
        // Irreversible: the original padding is not recorded, and restoring it
        // would only reintroduce the display bug.
    }
};
