<?php

namespace Kylin\Storage\Adapters;

use Kylin\Storage\Contracts\StorageAdapterInterface;
use Illuminate\Support\Facades\Storage;

class LocalAdapter implements StorageAdapterInterface
{
    private string $disk;

    public function __construct(array $config)
    {
        $this->disk = $config['disk'] ?? 'public';
    }

    public function upload(string $localPath, string $remotePath, array $options = []): string
    {
        $stream = fopen($localPath, 'rb');
        Storage::disk($this->disk)->put($remotePath, $stream);
        fclose($stream);
        return $remotePath;
    }

    public function download(string $remotePath, ?string $localPath = null): string
    {
        $content = Storage::disk($this->disk)->get($remotePath);

        if ($localPath) {
            file_put_contents($localPath, $content);
            return $localPath;
        }

        $tmpPath = tempnam(sys_get_temp_dir(), 'local_');
        file_put_contents($tmpPath, $content);
        return $tmpPath;
    }

    public function delete(string $remotePath): bool
    {
        return Storage::disk($this->disk)->delete($remotePath);
    }

    public function getUrl(string $remotePath): string
    {
        return Storage::disk($this->disk)->url($remotePath);
    }

    public function getSignedUrl(string $remotePath, int $expires = 3600): string
    {
        return $this->getUrl($remotePath);
    }

    public function exists(string $remotePath): bool
    {
        return Storage::disk($this->disk)->exists($remotePath);
    }

    public function getSize(string $remotePath): int
    {
        return Storage::disk($this->disk)->size($remotePath);
    }

    public function getMimeType(string $remotePath): string
    {
        return Storage::disk($this->disk)->mimeType($remotePath);
    }
}
