<?php

use App\Services\Whmcs\AgentRotator;
use App\Services\Whmcs\MarkdownCleaner;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

// Backfill two issues on existing AI-Triage internal notes:
//   1. author_name was hard-coded to "AI Triage" — should be the rotated
//      agent persona so the local portal timeline shows who "spoke".
//   2. Body still contains **bold** / ```code``` markdown that WHMCS
//      renders literally. The local mirror keeps the original text but
//      we also strip a clean copy so the timeline doesn't show asterisks.
//
// Idempotent: only touches rows author_name='AI Triage' OR where the body
// still contains markdown markers; re-running is a no-op once cleaned.
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('ticket_replies')) return;

        DB::table('ticket_replies')
            ->where('is_internal_note', true)
            ->whereIn('author_name', ['AI Triage', 'AI Triage ', 'ai_triage'])
            ->orderBy('id')
            ->chunkById(200, function ($rows) {
                foreach ($rows as $row) {
                    $agent = AgentRotator::pickForTicket((int) $row->ticket_id);
                    $cleaned = MarkdownCleaner::strip((string) $row->body);

                    DB::table('ticket_replies')->where('id', $row->id)->update([
                        'author_name' => $agent['display_name'],
                        'body'        => $cleaned,
                    ]);
                }
            });
    }

    public function down(): void
    {
        // Irreversible — we don't preserve the original author_name and
        // the markdown stripping is one-way (the local row never needed
        // the asterisks).
    }
};
