package com.petshop.backend.service;

import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;
import com.azure.core.util.BinaryData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AzureBlobService {

    private final BlobServiceClient client;
    private final String containerPrefix;

    public AzureBlobService(
            @Value("${azure.storage.connection-string:}") String connectionString,
            @Value("${azure.storage.container-prefix:petshop}") String containerPrefix) {
        this.containerPrefix = containerPrefix;
        this.client = (connectionString != null && !connectionString.isBlank())
                ? new BlobServiceClientBuilder().connectionString(connectionString).buildClient()
                : null;
    }

    public boolean isEnabled() {
        return client != null;
    }

    public void upload(String container, String blobName, byte[] bytes) {
        getContainerClient(container).getBlobClient(blobName).upload(BinaryData.fromBytes(bytes), true);
    }

    public byte[] download(String container, String blobName) {
        return getContainerClient(container).getBlobClient(blobName).downloadContent().toBytes();
    }

    public void delete(String container, String blobName) {
        getContainerClient(container).getBlobClient(blobName).deleteIfExists();
    }

    private BlobContainerClient getContainerClient(String container) {
        return client.createBlobContainerIfNotExists(containerPrefix + "-" + container);
    }
}
