<?php

namespace App\Http\Controllers\Contact;

use App\Http\Controllers\Controller;
use App\Models\Contact\Hub\ContactMessage;
use App\Models\Contact\Hub\ContactMessageAttachment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

class AttachmentDownloadController extends Controller
{
    public function __invoke(Request $request, ContactMessageAttachment $attachment): StreamedResponse
    {
        $this->authorise($request, $attachment);

        return Storage::disk($attachment->disk)->download(
            $attachment->path,
            $attachment->filename,
            ['Content-Type' => $attachment->mime ?: 'application/octet-stream'],
        );
    }

    public function preview(Request $request, ContactMessageAttachment $attachment): StreamedResponse
    {
        $this->authorise($request, $attachment);

        $mime = $attachment->mime ?: 'application/octet-stream';

        return Storage::disk($attachment->disk)->response(
            $attachment->path,
            $attachment->filename,
            ['Content-Type' => $mime, 'Content-Disposition' => 'inline'],
        );
    }

    private function authorise(Request $request, ContactMessageAttachment $attachment): void
    {
//        ContactMessage::withoutGlobalScopes()
//            ->where('id', $attachment->contact_message_id)
//            ->where('solicitor_id', $request->user()->solicitor_id)
//            ->firstOrFail();
//
//        abort_unless(
//            Storage::disk($attachment->disk)->exists($attachment->path),
//            404,
//            'Attachment file not found.'
//        );
    }
}
