<?php

namespace Modules\Media\Repositories;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Modules\Media\Models\Media;
use Modules\Media\Repositories\Interfaces\MediaRepositoryInterface;

class MediaRepository implements MediaRepositoryInterface
{
    public function __construct(
        private Media $model
    ) {}

    public function all(): Collection
    {
        return $this->model->all();
    }

    public function find(int $id): ?Media
    {
        return $this->model->find($id);
    }

    public function delete(int $id): bool
    {
        $media = $this->find($id);
        if ($media) {
            Storage::disk('public')->delete($media->path);
        }
        return $this->model->destroy($id);
    }

    public function getByMediable(string $mediableType, int $mediableId): Collection
    {
        return $this->model
            ->where('mediable_type', $mediableType)
            ->where('mediable_id', $mediableId)
            ->get();
    }

    public function upload(UploadedFile $file, string $type, Model $mediable): Media
    {
        $path = $file->store('media/' . $mediable->getTable(), 'public');

        return $this->model->create([
            'type' => $type,
            'path' => $path,
            'filename' => $file->getClientOriginalName(),
            'mime_type' => $file->getMimeType(),
            'size' => $file->getSize(),
            'mediable_type' => get_class($mediable),
            'mediable_id' => $mediable->id,
        ]);
    }

    public function uploadWithoutMediable(UploadedFile $file, string $type): Media
    {
        $path = $file->store('media/general', 'public');

        return $this->model->create([
            'type' => $type,
            'path' => $path,
            'filename' => $file->getClientOriginalName(),
            'mime_type' => $file->getMimeType(),
            'size' => $file->getSize(),
        ]);
    }

    public function count(): int
    {
        return $this->model->count();
    }
}
