<?php

namespace App\Observers;

use App\Assets\AssetLibrary;
use App\Models\Creative;
use Throwable;

/**
 * Turns a finished creative into something a campaign can use.
 *
 * An observer rather than a call at each completion point, because there are
 * three of them already (the wizard's synchronous image path, the image job and
 * the video render job) and a fourth would silently not be covered.
 *
 * Never lets a failure here fail the render. The creative is finished and the
 * user should see it; not yet being attachable is worth a log line, not losing
 * work that has already been paid for.
 */
class CreativeObserver
{
    public function __construct(private readonly AssetLibrary $assets) {}

    public function saved(Creative $creative): void
    {
        if ($creative->status !== 'completed' || blank($creative->asset_path)) {
            return;
        }

        // Not just "has no asset yet": a regenerated creative keeps its old
        // asset_id while asset_path points at the new render, and skipping
        // those left the campaign serving the image that was replaced.
        if ($creative->asset_id && $creative->asset?->path === $creative->asset_path) {
            return;
        }

        try {
            $this->assets->fromCreative($creative);
        } catch (Throwable $e) {
            report($e);
        }
    }
}
