<?php

namespace App\Console\Commands;

use App\Enum\Dsar\DsarStatus;
use App\Models\Dsar\Dsar;
use App\Services\DsarService;
use Illuminate\Console\Command;

/**
 * Re-renders the stored letter/email body of unsent DSARs from their source template.
 *
 * A DSAR's content/email_content is baked in at creation time (see
 * App\Components\Claim\Dsars::createDsars), so a change to a placeholder resolver only
 * reaches DSARs created afterwards. This sweep re-renders existing pre-send DSARs so
 * they pick up the corrected %solicitor_email% / %solicitor_phone% resolution (the DSAR
 * sender address / primary phone, rather than the deprecated firm-wide contact columns).
 *
 * Only pre-send DSARs (draft, approved) are touched — anything already sent keeps the
 * exact body that went to the institution. Each DSAR is re-rendered with its own author
 * (user_id) and reference so the user/reference placeholders resolve as they did at
 * creation rather than to the console's (null) auth user.
 */
class RerenderDraftDsars extends Command
{
    protected $signature = 'dsars:rerender-drafts
        {--dry-run : Count what would change without writing anything}';

    protected $description = 'Re-render the stored body of unsent (draft/approved) DSARs so they pick up corrected placeholder values.';

    public function handle(DsarService $service): int
    {
        $dryRun = (bool) $this->option('dry-run');

        // Console context: the BelongsToSolicitor global scope is inactive, so a
        // single pass covers every tenant.
        $dsars = Dsar::query()
            ->whereIn('status', DsarStatus::preSend())
            ->orderBy('id')
            ->get();

        if ($dsars->isEmpty()) {
            $this->info('No pre-send DSARs to re-render.');

            return self::SUCCESS;
        }

        $rerendered = 0;
        $skipped    = 0;

        foreach ($dsars as $dsar) {
            if ($dryRun) {
                $this->line(sprintf('  #%d  %s  (%s)', $dsar->id, $dsar->reference ?? 'no ref', $dsar->status));
                $rerendered++;
                continue;
            }

            if ($service->rebuildContent($dsar)) {
                $rerendered++;
            } else {
                $skipped++;
                $this->warn("  #{$dsar->id} skipped — no institution DSAR template.");
            }
        }

        $verb = $dryRun ? 'Would re-render' : 'Re-rendered';
        $this->info("{$verb} {$rerendered} DSAR(s)" . ($skipped ? ", skipped {$skipped}." : '.'));

        return self::SUCCESS;
    }
}
