<?php

namespace apexl\Io\modules\file\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\includes\System;
use apexl\Io\modules\file\services\File;
use Exception;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class fileController extends Controller
{
    public function __construct(
        protected File $file
    ) {
        parent::__construct();
    }

    /**
     * Generic file store method. Returns file entity data
     * @throws Exception
     */
    public function files(Request $request, Response $response): Response
    {
        $fileEntity = $this->file::getFileFromUpload($request);
        //Check we have a file we're allowed to upload and store, if not, throw an error
        if (!$this->file::isTypeAllowed($fileEntity->mime, $this->file::DEFAULT_ALLOWED_TYPES)) {
            $this->output::addMessage('core.file.upload', 'error', 'File type of '.$fileEntity->mime.' not allowed');

            return System::asJson($response, [], 403);
        }

        $path = $this->file::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 System::asJson($response);
    }
}
