<?php

namespace App\Domain\Shared\Traits;

use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;

/**
 * A file the browser uploaded a minute ago is not guaranteed to still be there
 * when the form is submitted.
 *
 * Livewire uploads in two steps: the file lands in `livewire-tmp` on its own
 * request, and the component reads it on a later one. Between the two, the
 * temporary file can be gone — the container was redeployed (every push
 * redeploys, and the tmp directory is not persistent), Livewire's own cleanup
 * removed it, or the phone resent the form after the app had restarted.
 *
 * What happened then was a 500. Every read of the file — `max:5120` in the
 * rules calls getSize(), so validation is the first to touch it — throws
 * Flysystem's UnableToRetrieveMetadata, which nothing catches. A receptionist
 * standing at the desk with a receipt on their phone sees an error page and a
 * support code (eab81218-…, 2026-09-02, an expense receipt from an iPhone).
 *
 * The file being gone is not an exceptional condition, it is Tuesday. It gets
 * a sentence in Arabic asking for the file again, and the property is cleared
 * so the next attempt starts clean.
 */
trait ChecksTemporaryUploads
{
    /**
     * True when there is a pending upload on this property and its backing
     * file has vanished.
     *
     * A non-upload value (null, or an already-stored path) is not missing —
     * there is simply nothing to check.
     */
    protected function uploadHasVanished(mixed $file): bool
    {
        if ($file instanceof TemporaryUploadedFile) {
            try {
                return ! $file->exists();
            } catch (\Throwable) {
                // The disk itself is unreachable: treat it as gone rather than
                // letting a storage exception reach the browser.
                return true;
            }
        }

        if (is_array($file)) {
            foreach ($file as $one) {
                if ($this->uploadHasVanished($one)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Guard a submit handler. Returns false when the caller should stop,
     * having already told the user what to do.
     */
    protected function temporaryUploadIsUsable(string $property, mixed $file): bool
    {
        if (! $this->uploadHasVanished($file)) {
            return true;
        }

        $this->{$property} = is_array($file) ? [] : null;

        $this->addError($property, __('انتهت صلاحية الملف المرفوع — من فضلك اختر الملف مرة أخرى وأعد الرفع.'));

        return false;
    }
}
