<?php

namespace Daylight\Core\Modules\MediaLibrary\Http\Controllers\API;

use Daylight\Core\Http\Controllers\Controller;
use Daylight\Core\Modules\MediaLibrary\Http\Requests\StoreMediaRequest;
use Daylight\Core\Modules\MediaLibrary\Models\Directory;
use Daylight\Core\Modules\MediaLibrary\Models\Media;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class MediaController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:read:media', only: ['index']),
        ];
    }

    public function index(Request $request)
    {
        if ($request->has('directory')) {
            $directory = Directory::query()
                ->whereId(request()->get('directory'))
                ->firstOrFail();

            if ($directory) {
                return [
                    'currentDirectory' => $directory,
                    'directories' => Directory::query()->whereParentId($directory->id)->get(),
                    'files' => $directory->media()->paginate(40),
                ];
            }
        }

        return [
            'currentDirectory' => null,
            'directories' => Directory::query()->whereNull('parent_id')->get(),
            'files' => Media::query()->whereDirectoryId(null)->paginate(40),
        ];
    }

    public function store(StoreMediaRequest $request)
    {
        return collect($request->safe()->files)->map(function (array $file) use ($request) {
            return Media::create([
                'directory_id' => $request->safe()->currentDirectory ?? null,
                'handle' => str_ireplace(config('services.bytescale.path'), '', $file['filePath']),
                'type' => $file['originalFile']['mime'],
                'name' => $file['originalFile']['originalFileName'],
                'size' => $file['originalFile']['size'],
            ]);
        });
    }

    public function destroy($media)
    {
        $media = Media::query()
            ->whereId($media)
            ->firstOrFail();

        $media->delete();

        return response()->json(null, 204);
    }
}
