<?php

namespace App;

use App\Facades\Settings;
use Illuminate\Support\Facades\Config;
use Mtc\ContentManager\Contracts\Media;
use Mtc\ContentManager\Contracts\MediaTag;
use Mtc\ContentManager\Contracts\MediaUse;
use Mtc\ContentManager\MediaRepository as BaseMediaRepository;
use Mtc\ContentManager\Models\MediaFolder;

class MediaRepository extends BaseMediaRepository
{
    public function __construct(Media $model, MediaUse $mediaUse, MediaTag $tag, MediaFolder $folder)
    {
        parent::__construct($model, $mediaUse, $tag, $folder);
        if (Settings::get('filesystem-custom-s3-bucket-enabled')) {
            $this->setCustomStorage();
        }
    }

    /**
     * File storage prefix for multi-tenancy
     *
     * @return string
     */
    #[\Override]
    public function storagePrefix(): string
    {
        if (tenancy()->initialized && !Settings::get('filesystem-custom-s3-bucket-enabled')) {
            return tenant('id') . '/';
        }

        return parent::storagePrefix();
    }

    private function setCustomStorage(): void
    {
        $config = Config::get('filesystems.disks.' . Config::get('filesystems.default_media'));
        $config['key'] = Settings::get('filesystem-custom-s3-bucket-access-key-id');
        $config['secret'] = Settings::get('filesystem-custom-s3-bucket-access-key');
        $config['region'] = Settings::get('filesystem-custom-s3-bucket-region');
        $config['bucket'] = Settings::get('filesystem-custom-s3-bucket-bucket');
        $config['endpoint'] = Settings::get('filesystem-custom-s3-bucket-endpoint');
        $config['cdn_endpoint'] = Settings::get('filesystem-custom-s3-bucket-cnd-endpoint');
        Config::set('filesystems.disks.' . tenant('id'), $config);
        Config::set('filesystems.default_media', tenant('id'));
    }
}
