<?php

namespace apexl\Io\modules\file\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\modules\file\services\FileService;
use Exception;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class fileController extends Controller
{
    /**
     * Generic file store method. Returns file entity data
     * @throws Exception
     */
    public function __invoke(FileService $fileService, ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $fileEntity = $fileService->getFileFromUpload($request);
        //Check we have a file we're allowed to upload and store, if not, throw an error
        if (!$fileService->isTypeAllowed($fileEntity->mime, FileService::DEFAULT_ALLOWED_TYPES)) {
            $this->output->addMessage(
                'core.file.upload',
                'error',
                'File type of ' . $fileEntity->mime . ' not allowed'
            );

            return $this->json($response, [], 403);
        }

        $path = $fileService->storeUploadedFile($fileEntity->getMetadata('uploadedFile'));
        $fileEntity->path = $path;
        $fileEntity->store();

        $this->output->addMessage('core.file.upload', 'success', 'File type of ' . $fileEntity->mime . ' uploaded.');
        $this->output->addResponse($request, ['fid' => $fileEntity->id]);

        return $this->json($response);
    }
}
