<?php

namespace Modules\SmartStorage\Entities\Drivers;

use Aws\S3\S3Client;
use League\Flysystem\AwsS3V3\AwsS3V3Adapter;
use League\Flysystem\FilesystemAdapter;
use Modules\SmartStorage\Entities\Contracts\StorageBackendDriver;
use Modules\SmartStorage\Entities\SsSetting;

/**
 * AWS S3 (or any S3-compatible endpoint) backed by league/flysystem-aws-s3-v3.
 * Credentials are read from the encrypted ss_settings.credentials blob under the
 * "s3" key, falling back to the app's existing s3 disk config / env.
 */
class S3BackendDriver implements StorageBackendDriver
{
    public function key(): string
    {
        return 's3';
    }

    public function label(): string
    {
        return 'AWS S3 / S3-compatible';
    }

    public function isAvailable(): bool
    {
        return class_exists(S3Client::class) && class_exists(AwsS3V3Adapter::class);
    }

    protected function config(SsSetting $settings): array
    {
        $c = $settings->credentialsArray()['s3'] ?? [];

        return [
            'key'      => $c['key']      ?? config('filesystems.disks.s3.key'),
            'secret'   => $c['secret']   ?? config('filesystems.disks.s3.secret'),
            'region'   => $c['region']   ?? config('filesystems.disks.s3.region', 'us-east-1'),
            'bucket'   => $c['bucket']   ?? config('filesystems.disks.s3.bucket'),
            'endpoint' => $c['endpoint'] ?? config('filesystems.disks.s3.endpoint'),
            'prefix'   => $c['prefix']   ?? '',
            'use_path_style_endpoint' => (bool) ($c['use_path_style_endpoint'] ?? config('filesystems.disks.s3.use_path_style_endpoint', false)),
        ];
    }

    public function validateConfig(SsSetting $settings): array
    {
        $errors = [];
        $cfg = $this->config($settings);
        foreach (['key', 'secret', 'region', 'bucket'] as $req) {
            if (empty($cfg[$req])) {
                $errors[] = "S3: missing {$req}";
            }
        }
        return $errors;
    }

    public function makeAdapter(SsSetting $settings): FilesystemAdapter
    {
        $cfg = $this->config($settings);

        $clientConfig = [
            'version'     => 'latest',
            'region'      => $cfg['region'],
            'credentials' => [
                'key'    => $cfg['key'],
                'secret' => $cfg['secret'],
            ],
        ];
        if (!empty($cfg['endpoint'])) {
            $clientConfig['endpoint'] = $cfg['endpoint'];
            $clientConfig['use_path_style_endpoint'] = $cfg['use_path_style_endpoint'];
        }

        $client = new S3Client($clientConfig);

        return new AwsS3V3Adapter($client, $cfg['bucket'], (string) $cfg['prefix']);
    }
}
