import { readFileSync } from "fs";
import { SimpleAuthenticationDetailsProvider, Region } from "oci-common";
import { ObjectStorageClient } from "oci-objectstorage";

const userOcId = process.env.USER_OCID!;
const tenancyOcId = process.env.TENANCY_OCID!;
const privateKeyPath = process.env.PRIVATE_KEY_PATH!;
const fingerprint = process.env.FINGERPRINT!;
const namespace = process.env.NAMESPACE!;

if (!userOcId || !tenancyOcId || !privateKeyPath || !fingerprint || !namespace) {
    throw new Error(
        "Faltan variables de entorno de Oracle (USER_OCID, TENANCY_OCID, PRIVATE_KEY_PATH, FINGERPRINT, NAMESPACE)"
    );
}

const privateKey = readFileSync(privateKeyPath, "utf-8");

const region = Region.fromRegionId("sa-saopaulo-1");

const provider = new SimpleAuthenticationDetailsProvider(
    tenancyOcId,
    userOcId,
    fingerprint,
    privateKey,
    null,
    region
);

const client = new ObjectStorageClient({ authenticationDetailsProvider: provider });

export const subirArchivo = async (bucketName: string, objectName: string, data: Buffer) => {
    const request = {
        namespaceName: namespace,
        bucketName,
        objectName,
        putObjectBody: data,
    };
    return client.putObject(request);
};

export const descargarArchivo = async (bucketName: string, objectName: string) => {
    const request = {
        namespaceName: namespace,
        bucketName,
        objectName,
    };
    return client.getObject(request);
};
