<?php

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

// Old reply rows that were synced from WHMCS before the persona-mapping fix
// stored author_name as whatever WHMCS returned in the "admin" field — often
// the bare username ("tanvir") or, worse, the admin's email
// ("admin@hostseba.com") when the WHMCS admin record had no firstname/lastname
// set. Both look terrible in the timeline.
//
// This migration walks SupportAgent personas and rewrites matching reply
// rows' author_name to the persona's display_name. Looks up by:
//   - direct match on whmcs_admin_username
//   - email local part (e.g. "tanvir@x" → match persona "tanvir")
//
// Idempotent — only touches rows where author_name still equals one of the
// raw WHMCS attributions (not rows already showing the display_name).
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('ticket_replies') || ! Schema::hasTable('support_agents')) return;

        $agents = DB::table('support_agents')
            ->select('whmcs_admin_username', 'display_name')
            ->whereNotNull('whmcs_admin_username')
            ->where('whmcs_admin_username', '!=', '')
            ->get();

        foreach ($agents as $a) {
            $username = $a->whmcs_admin_username;
            $displayName = $a->display_name;
            if (! $displayName) continue;

            // Match the bare username AND any email whose local part is the
            // username (covers "tanvir" stored as "tanvir@hostseba.com").
            DB::table('ticket_replies')
                ->where(function ($q) use ($username) {
                    $q->where('author_name', $username)
                      ->orWhere('author_name', 'like', $username . '@%')
                      ->orWhere('whmcs_admin_username', $username);
                })
                ->where('author_name', '!=', $displayName)
                ->update(['author_name' => $displayName]);
        }
    }

    public function down(): void
    {
        // Irreversible — we'd have to remember each row's original raw value.
    }
};
