<?php

namespace App\Jobs;

use App\Models\Video;
use App\Services\NasSyncService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    public int $tries   = 3;
    public int $backoff = 60;

    public function __construct(public readonly Video $video) {}

    public function handle(NasSyncService $nas): void
    {
        if (! $nas->isEnabled()) return;
        try {
            $nas->syncVideo($this->video);

            // Audio/music uploads have no further processing jobs, so it's safe
            // to remove the local file immediately after a successful NAS push.
            // Video uploads must keep the local file until GenerateHlsJob finishes.
            if ($this->video->type === 'music') {
                $nas->deleteLocalVideo($this->video);
            }
            $nas->deleteLocalAssets($this->video);
            $nas->pruneLocalVideoDir($this->video);
        } catch (\Throwable $e) {
            \Illuminate\Support\Facades\Log::error(
                'NasSyncVideoJob failed for video #' . $this->video->id .
                ' ("' . $this->video->title . '"): ' . $e->getMessage() .
                ' — local files kept. Run `php artisan nas:repair --force` to retry.'
            );
        }
    }
}
