<?php

namespace classes;

use interfaces\minio_pdfs_i;
use traits\minio_t;

class pdf_store implements minio_pdfs_i
{
    use minio_t;

    public function __construct()
    {
        self::setBucket('pdfs'); // Change the bucket to 'pdfs'
    }

    /**
     * @inheritDoc
     */
    public function pdf_exists(int $pdf_id): bool
    {
        // Check if the file exists
        $objects = self::getS3Client()->listObjects([
            'Bucket' => self::getBucket(),
            'Prefix' => self::get_pdf_key_name($pdf_id)
        ]);
        return count($objects['Contents'] ?? []) > 0;
    }

    /**
     * @inheritDoc
     */
    public function get_pdf_key_name(string $id): string
    {
        // Generate the PDF key name
        return 'pdf_' . $id . '.pdf';
    }

    public function getDownloadUrl(int $id): string
    {
        return self::getPresignedUrl(self::get_pdf_key_name($id));
    }

    /**
     * @param string $file
     * @return string The path to the downloaded file
     */
    public function download(string $file): string
    {
        $path = '/tmp/' . $file;
        $result = self::getS3Client()->getObject([
            'Bucket' => self::getBucket(),
            'Key' => $file,
            'SaveAs' => $path
        ]);
        return $path;
    }

    public function isFileInStore(string $file): bool
    {
        return self::getS3Client()->doesObjectExist(self::getBucket(), $file);
    }

    /**
     * @inheritDoc
     */
    public function upload(string $pdf_id, string $file_path): string
    {
        // Upload the file to the Minio bucket
        return self::uploadFile(
            self::get_pdf_key_name($pdf_id),
            $file_path
        );
    }
}