<?php

namespace App\Observers;

use App\Models\DailyClosing;
use App\Services\DailyBranchReportService;
use Illuminate\Support\Facades\DB;
use Throwable;

class DailyClosingObserver
{
    public function updated(DailyClosing $closing): void
    {
        if (! $closing->wasChanged('status') || $closing->status !== 'confirmed') {
            return;
        }

        $closingId = $closing->id;

        DB::afterCommit(function () use ($closingId): void {
            try {
                $confirmedClosing = DailyClosing::withoutGlobalScopes()->find($closingId);
                if (! $confirmedClosing || $confirmedClosing->status !== 'confirmed') {
                    return;
                }

                app(DailyBranchReportService::class)->archiveAndDispatch($confirmedClosing);
            } catch (Throwable $exception) {
                report($exception);
            }
        });
    }
}
