<?php
use Illuminate\Http\RedirectResponse;

class FilesController
{
    /**
     * Let the user download the file directly from S3.
     *
     * This prevents that large files are piped through webapp's PHP process.
     *
     * @link https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.S3Client.html#_createPresignedRequest
     */
    protected function getRedirectFileResponse(string $diskName, string $path): RedirectResponse
    {
        $disk = Storage::disk($diskName);
        if (!$disk->has($path)) {
            abort(Response::HTTP_NOT_FOUND, 'File does not exist');
        }

        /* @var \League\Flysystem\AwsS3v3\AwsS3Adapter $s3Adapter */
        $s3Adapter = $disk->getDriver()->getAdapter();

        /* @var \Aws\S3\S3Client $s3Client */
        $s3Client = $s3Adapter->getClient();

        $reqOptions = [
            'Bucket' => $s3Adapter->getBucket(),
            'Key'    => $s3Adapter->applyPathPrefix($path),
        ];

        $command = $s3Client->getCommand('GetObject', $reqOptions);
        $expiration = new \DateTime('+1 day');

        $request = $s3Client->createPresignedRequest($command, $expiration);
        $signedUrl = (string) $request->getUri();

        //return a cachable temporary redirect
        return redirect()->to($signedUrl, 307)
            ->setPublic()
            ->setExpires($expiration);
    }
}