<?php

namespace App\Jobs;

use App\Models\CronRunLog;
use App\Services\CronLogService;
use App\Services\RepairToolService;
use Carbon\Carbon;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class RunWalletReconciliationJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(public readonly string $runDate)
    {
    }

    public function handle(RepairToolService $repairToolService, CronLogService $cronLogService): void
    {
        $runDate = Carbon::parse($this->runDate);
        $runKey = 'wallet-reconciliation-'.$runDate->format('Ymd');

        $existing = CronRunLog::query()
            ->where('run_key', $runKey)
            ->where('status', 'success')
            ->first();

        if ($existing) {
            return;
        }

        $log = $cronLogService->start('wallet-reconciliation', $runKey, [
            'run_date' => $runDate->toDateString(),
        ]);

        try {
            $repairToolService->recalculateWallet();
            $cronLogService->finish($log, 'success', 'Wallet balances reconciled from immutable ledger.');
        } catch (Exception $exception) {
            $cronLogService->finish($log, 'failed', null, $exception->getMessage());
            throw $exception;
        }
    }
}
