<?php

namespace Shopping\Feed;

use Aws\S3\S3Client;
use Aws\Exception\AwsException;

class S3FeedPublisher {

    private S3Client $s3;
    private string $bucket;

    public function __construct(string $region, string $bucket, string $key, string $secret) {
        $this->bucket = $bucket;

        $this->s3 = new S3Client([
            'version' => 'latest',
            'region' => $region,
            'credentials' => [
                'key'    => $key,
                'secret' => $secret,
            ],
        ]);
    }

    /**
     * Publish feed and update latest pointer
     */
    public function publish(
        int    $publisherId,
        string $localGzPath,
        string $dateYmd
    ): string {

        $datedKey  = "shopping/shopping-products_{$publisherId}_{$dateYmd}.csv.gz";
        $latestKey = "shopping/shopping-products_{$publisherId}_latest.csv.gz";

        // 1️⃣ Upload dated file
        $this->uploadFile($localGzPath, $datedKey);

        // 2️⃣ Update latest pointer (COPY, not symlink)
        $this->copyObject($datedKey, $latestKey);

        return "s3://{$this->bucket}/{$datedKey}";
    }

    private function uploadFile(string $path, string $key): void {
        try {
            $this->s3->putObject([
                'Bucket' => $this->bucket,
                'Key' => $key,
                'SourceFile' => $path,
                'ContentType' => 'application/gzip',
                'ACL' => 'private',
            ]);
        } catch (AwsException $e) {
            throw new \RuntimeException(
                "S3 upload failed: " . $e->getAwsErrorMessage()
            );
        }
    }

    private function copyObject(string $sourceKey, string $targetKey): void {
        try {
            $this->s3->copyObject([
                'Bucket' => $this->bucket,
                'CopySource' => "{$this->bucket}/{$sourceKey}",
                'Key' => $targetKey,
                'ACL' => 'private',
            ]);
        } catch (AwsException $e) {
            throw new \RuntimeException(
                "S3 latest update failed: " . $e->getAwsErrorMessage()
            );
        }
    }
}
