<?php

namespace App\Services\Models;

use App\Models\File;
use App\Services\FileUploadService;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

class FileService
{
    protected $model;

    public function setModel($model): static
    {
        $this->model = $model;
        return $this;
    }

    public function add(int $fileId, array $extraData = []): void
    {
        $this->model->files()->syncWithoutDetaching([$fileId => ['data' => json_encode($extraData)]]);
    }

    public function upload(UploadedFile $uploadedFile, array $extraData = []): File
    {
        $service = new FileUploadService(
            file: $uploadedFile,
            path: $extraData['path'] ?? 'files',
            disk: $extraData['disk'] ?? 'public_upload',
        );
        $info = $service->upload();

        $file = File::create([
            'name' => $info['original_name'],
            'extension' => $info['extension'],
            'mime' => $info['mime_type'],
            'size' => $info['size'],
            'path' => $info['stored_path'],
            'disk' => $info['disk'],
        ]);


        if ($this->model != null) {
            $this->model->files()->attach($file->id, ['data' => json_encode(array_merge($extraData))]);
        }

        return $file;
    }

    public function remove(int $fileId): void
    {
        $this->model->files()->detach($fileId);
    }

    public function destroy(int $fileId): void
    {
        $file = File::findOrFail($fileId);
        Storage::disk($file->disk)->delete($file->path);
        $this->remove($fileId);
        $file->delete();
    }

    public function get(): ?File
    {
        return $this->model->files()->first();
    }
}
