<?php

namespace App\Repositories;

use Abedin\Maker\Repositories\Repository;
use App\Models\Media;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class MediaRepository extends Repository
{
    public static function model()
    {
        return Media::class;
    }

    public static function storeByRequest($fileInputName, $folderName = 'default')
    {
        $file = $fileInputName;
        $path = Storage::disk('public')->put('/' . trim($folderName, '/'), $file);
        $extension = $file->extension();

        return self::create([
            'original_name' => $file->getClientOriginalName(),
            'src'           => $path,
            'type'          => $file->getClientMimeType(),
            'extension'     => $extension,
            'added_by'      => Auth::id(),
        ]);
    }

    public static function updateByRequest($model, $fileInputName, $folderName = 'default')
    {
        $oldMedia = self::find($model?->thumbnail_id);
        $file = $fileInputName;
        $path = Storage::disk('public')->put('/' . trim($folderName, '/'), $file);
        $extension = $file->extension();

        if ($oldMedia) {
            $oldPath = $oldMedia->src;
            if (Storage::disk('public')->exists($oldPath)) {
                Storage::disk('public')->delete($oldPath);
            }

            $oldMedia->original_name = $file->getClientOriginalName();
            $oldMedia->src           = $path;
            $oldMedia->type          = $file->getClientMimeType();
            $oldMedia->extension     = $extension;
            $oldMedia->added_by      = Auth::id();
            $oldMedia->save();

            return $oldMedia;
        }

        return self::create([
            'original_name' => $file->getClientOriginalName(),
            'src'           => $path,
            'type'          => $file->getClientMimeType(),
            'extension'     => $extension,
            'added_by'      => Auth::id(),
        ]);
    }
}
