<?php

namespace App\Services;

use App\Models\Cattle;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class CattlePhotoService
{
    public function store(Cattle $cattle, UploadedFile $file): string
    {
        $this->deleteFile($cattle);

        $extension = strtolower($file->getClientOriginalExtension() ?: 'jpg');
        if (! in_array($extension, ['jpg', 'jpeg', 'png', 'webp', 'gif'], true)) {
            $extension = 'jpg';
        }

        $path = $file->storeAs(
            'cattle/'.$cattle->id,
            'photo-'.Str::uuid().'.'.$extension,
            'public',
        );

        $cattle->update(['photo_path' => $path]);

        return $path;
    }

    public function delete(Cattle $cattle): void
    {
        $this->deleteFile($cattle);
        $cattle->update(['photo_path' => null]);
    }

    private function deleteFile(Cattle $cattle): void
    {
        if ($cattle->photo_path && Storage::disk('public')->exists($cattle->photo_path)) {
            Storage::disk('public')->delete($cattle->photo_path);
        }
    }
}
