<?php

namespace Config;

use CodeIgniter\Config\BaseConfig;

class Storage extends BaseConfig
{
    /** @var 'local'|'s3' */
    public string $driver = 'local';

    /** When using S3, also write a copy to local disk (migration / fallback). */
    public bool $retainLocal = false;

    public string $localRoot;

    public string $s3Bucket = '';

    public string $s3Region = 'ap-south-1';

    /** Optional key prefix, e.g. uat or prod */
    public string $s3Prefix = '';

    public string $s3AccessKey = '';

    public string $s3SecretKey = '';

    /** Default presigned URL TTL in seconds. */
    public int $presignedTtl = 900;

    public function __construct()
    {
        parent::__construct();

        $driver = getenv('FILE_STORAGE_DRIVER') ?: 'local';
        $this->driver = in_array($driver, ['local', 's3'], true) ? $driver : 'local';

        $this->retainLocal = filter_var(getenv('RETAIN_LOCAL') ?: 'false', FILTER_VALIDATE_BOOLEAN);
        $this->localRoot   = rtrim(WRITEPATH, '/\\') . DIRECTORY_SEPARATOR;

        $this->s3Bucket    = getenv('AWS_BUCKET') ?: '';
        $this->s3Region    = getenv('AWS_DEFAULT_REGION') ?: 'ap-south-1';
        $this->s3Prefix    = trim(getenv('AWS_S3_PREFIX') ?: '', '/');
        $this->s3AccessKey = getenv('AWS_ACCESS_KEY_ID') ?: '';
        $this->s3SecretKey = getenv('AWS_SECRET_ACCESS_KEY') ?: '';

        $ttl = getenv('AWS_PRESIGNED_TTL');
        if ($ttl !== false && $ttl !== '' && is_numeric($ttl)) {
            $this->presignedTtl = max(60, (int) $ttl);
        }
    }
}
