<?php

namespace Lucent\File;

use Illuminate\Http\UploadedFile;
use Lucent\Channel\ChannelService;
use Lucent\LucentException;
use Lucent\Record\File;
use Lucent\Record\QueryRecord;
use Lucent\Schema\Schema;
use Lucent\Schema\Type;

class FileService
{

    public function __construct(
        public ChannelService $channelService
    )
    {
    }

    public function getPath(QueryRecord $file): string
    {
        return $this->channelService->channel->url. "/storage/".$file->_file->path;
    }

    /**
     * @throws LucentException
     */
    public static function create(Schema $schema, string $uploadFromUrl, array $file): FileUploadResult
    {
        $emptyUploadUrl = empty($uploadFromUrl);
        $emptyFileData = empty($file);

        if ($schema->type === Type::FILES && $emptyUploadUrl && $emptyFileData) {
            throw new LucentException("No file data submitted");
        } elseif ($schema->type !== Type::FILES && !($emptyUploadUrl && $emptyFileData)) {
            throw new LucentException("You can't upload a file to a regular record");
        } elseif ($schema->type !== Type::FILES) {
            return new FileUploadResult(
                recordFile: null, duplicateId: "", isDuplicate: false
            );
        }

        if (!$emptyUploadUrl) {
            $file = self::uploadFileFromUrl($uploadFromUrl);
            return uploadFile($schema, $file);
        }

        return new FileUploadResult(
            recordFile: File::fromArray($file), duplicateId: "", isDuplicate: false
        );
    }

    /**
     * @throws LucentException
     */
    private static function uploadFileFromUrl(string $url): UploadedFile
    {

        $pathinfo = pathinfo($url);
        $contents = file_get_contents($url);
        if ($contents === false) {
            throw new LucentException("Failed to upload file from url");
        }
        $file = '/tmp/' . $pathinfo['basename'];
        file_put_contents($file, $contents);
        return new UploadedFile($file, $pathinfo['basename']);
    }
}
