<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Requests\File\StoreFileUploadRequest;
use App\Support\ApiResponse;
use App\Support\FileUrl;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

class FileUploadController extends Controller
{
    public function store(StoreFileUploadRequest $request)
    {
        $directory = sprintf(
            '%d/%s/%s',
            $request->user()->id,
            now()->format('Y'),
            now()->format('m')
        );

        $paths = array_map(
            function (UploadedFile $file) use ($directory): string {
                $storagePath = Storage::disk(FileUrl::DISK)->putFile($directory, $file);

                return FileUrl::toStoredPath($storagePath);
            },
            $request->uploadedFiles()
        );

        $urls = array_map(
            fn (string $path): ?string => FileUrl::url($path),
            $paths
        );

        return ApiResponse::response(
            data: count($urls) === 1 ? $urls[0] : $urls,
            message: count($urls) === 1
                ? 'فایل با موفقیت آپلود شد.'
                : 'فایل‌ها با موفقیت آپلود شدند.',
            status: 201,
            meta: [
                'paths' => count($paths) === 1 ? $paths[0] : $paths,
            ]
        );
    }
}
