<?php

namespace Modules\SmartStorage\Entities\Drivers;

use League\Flysystem\FilesystemAdapter;
use Modules\SmartStorage\Entities\Contracts\StorageBackendDriver;
use Modules\SmartStorage\Entities\SsSetting;
use RuntimeException;

/**
 * Google Drive backend (scaffold).
 *
 * The Flysystem v3 Google Drive adapter is not bundled with this app. To enable:
 *   composer require masbug/flysystem-google-drive-ext
 * then create OAuth credentials (client id/secret + refresh token) and save them
 * under ss_settings.credentials["gdrive"]. Until the package is present this
 * driver reports isAvailable() = false and is shown but disabled in the UI.
 */
class GoogleDriveBackendDriver implements StorageBackendDriver
{
    private const ADAPTER_CLASS = \Masbug\Flysystem\GoogleDriveAdapter::class;

    public function key(): string
    {
        return 'gdrive';
    }

    public function label(): string
    {
        return 'Google Drive' . ($this->isAvailable() ? '' : ' (install masbug/flysystem-google-drive-ext)');
    }

    public function isAvailable(): bool
    {
        return class_exists(self::ADAPTER_CLASS) && class_exists(\Google\Client::class);
    }

    public function validateConfig(SsSetting $settings): array
    {
        if (!$this->isAvailable()) {
            return ['Google Drive: run `composer require masbug/flysystem-google-drive-ext` to enable this backend.'];
        }

        $c = $settings->credentialsArray()['gdrive'] ?? [];
        $errors = [];
        foreach (['client_id', 'client_secret', 'refresh_token'] as $req) {
            if (empty($c[$req])) {
                $errors[] = "Google Drive: missing {$req}";
            }
        }
        return $errors;
    }

    public function makeAdapter(SsSetting $settings): FilesystemAdapter
    {
        if (!$this->isAvailable()) {
            throw new RuntimeException(
                'Google Drive backend requires the masbug/flysystem-google-drive-ext package.'
            );
        }

        $c = $settings->credentialsArray()['gdrive'] ?? [];

        $client = new \Google\Client();
        $client->setClientId($c['client_id']);
        $client->setClientSecret($c['client_secret']);
        $client->refreshToken($c['refresh_token']);

        $service = new \Google\Service\Drive($client);

        $adapterClass = self::ADAPTER_CLASS;
        $rootFolder = $c['root_folder_id'] ?? '/';

        return new $adapterClass($service, $rootFolder);
    }
}
