<?php

namespace Modules\SmartStorage\Entities\Drivers;

use League\Flysystem\FilesystemAdapter;
use Modules\SmartStorage\Entities\Contracts\StorageBackendDriver;
use Modules\SmartStorage\Entities\SsSetting;
use Spatie\Dropbox\Client as DropboxClient;
use Spatie\FlysystemDropbox\DropboxAdapter;

/**
 * Dropbox backend via spatie/flysystem-dropbox. The access token is read from
 * the encrypted ss_settings.credentials["dropbox"]["token"], falling back to the
 * existing dropbox disk config / DROPBOX_ACCESS_TOKEN env.
 */
class DropboxBackendDriver implements StorageBackendDriver
{
    public function key(): string
    {
        return 'dropbox';
    }

    public function label(): string
    {
        return 'Dropbox';
    }

    public function isAvailable(): bool
    {
        return class_exists(DropboxClient::class) && class_exists(DropboxAdapter::class);
    }

    protected function token(SsSetting $settings): ?string
    {
        $c = $settings->credentialsArray()['dropbox'] ?? [];
        return $c['token']
            ?? config('filesystems.disks.dropbox.authorization_token')
            ?? env('DROPBOX_ACCESS_TOKEN');
    }

    public function validateConfig(SsSetting $settings): array
    {
        return empty($this->token($settings)) ? ['Dropbox: missing access token'] : [];
    }

    public function makeAdapter(SsSetting $settings): FilesystemAdapter
    {
        $client = new DropboxClient($this->token($settings));
        $prefix = $settings->credentialsArray()['dropbox']['prefix'] ?? '';

        return new DropboxAdapter($client, (string) $prefix);
    }
}
