<?php

namespace App\Support;

use App\Models\Asset;
use Illuminate\Support\Facades\Storage;
use Throwable;

/**
 * Whether an asset's original file can be read, rather than whether one call says
 * it exists.
 *
 * Mohsin generated a creative on 7 Oct and was told "Creative 14 is attached here,
 * but its original file is unavailable, so it couldn't be uploaded to the ad
 * account". The file was there. Fetched from production at the exact path on the
 * asset row it returned 200 and 1,240,773 bytes, matching assets.bytes to the
 * byte, twelve requests out of twelve, with a last-modified equal to
 * assets.updated_at. It had been on disk for six minutes when the tool said it was
 * gone, and nothing distinguished it from creative 10, which the same reply was
 * still offering: same owner, same public disk, same generated source, same rough
 * size.
 *
 * Why Storage::disk('public')->exists() disagreed with the bytes is still unknown.
 * I could not reproduce it and I am not going to guess at it here; it wants a look
 * at the box, starting with whether public/storage is a symlink and where the
 * configured disk root actually points.
 *
 * What can be fixed without knowing is the reasoning. Both the chooser and the
 * uploader asked exists() and treated false as proof, then told the buyer their
 * file had gone. On a local disk that is one stat, and a stat is weaker evidence
 * than opening the file. So false now means "not confirmed" and the question is
 * settled by trying to read: if the bytes are reachable the upload can proceed,
 * whatever exists() thinks, because reaching the bytes is the only thing the
 * upload actually needs.
 *
 * Nothing speculative is kept here. Clearing the stat cache and testing the
 * resolved local path were both tried and both removed again, because removing
 * them changed no test: fopen does not consult the stat cache, so the read below
 * already covers everything they would have caught. The sequence is deliberately
 * the one ReviewAssets::withLocalAssetPath already used to produce the bytes for
 * upload - it was sound, and it sat behind the exists() gate that threw before any
 * of it could run.
 */
class AssetOriginal
{
    /**
     * True when the bytes can be got at.
     *
     * Cheap in the ordinary case: one stat that says yes and nothing else runs.
     * The extra work happens only where the answer was going to be "unavailable",
     * which is the answer worth being sure about.
     */
    public static function isReadable(?Asset $asset): bool
    {
        if ($asset === null || blank($asset->path)) {
            return false;
        }

        try {
            $disk = Storage::disk($asset->disk ?: 'local');
        } catch (Throwable) {
            // A disk the application no longer configures. Nothing to read from,
            // and not something to raise from inside a readability check.
            return false;
        }

        try {
            if ($disk->exists($asset->path)) {
                return true;
            }
        } catch (Throwable) {
            // Fall through to the read: a throwing exists() is no more
            // conclusive than a false one.
        }

        // The last word, because opening the stream is what the upload needs to
        // succeed. A stream rather than get(): these are megabyte images and
        // videos, and the question is only whether the bytes are reachable, so
        // there is no reason to pull them all into memory to find out.
        $stream = null;

        try {
            $stream = $disk->readStream($asset->path);

            return is_resource($stream);
        } catch (Throwable) {
            return false;
        } finally {
            if (is_resource($stream)) {
                fclose($stream);
            }
        }
    }

    /** The inverse, for the call sites that are looking for the bad case. */
    public static function isMissing(?Asset $asset): bool
    {
        return ! self::isReadable($asset);
    }
}
