<?php

namespace App\Http\Controllers\Api\Messaging;

use App\Http\Controllers\Controller;
use App\Models\MessageAttachment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

class AttachmentController extends Controller
{
    public function show(Request $request, int $id)
    {
        $attachment = MessageAttachment::query()
            ->with('message:id,conversation_id')
            ->findOrFail($id);

        $conversationId = (int) ($attachment->message?->conversation_id ?? 0);
        abort_if($conversationId <= 0, 404, 'Attachment not available.');

        $authorized = \App\Models\ConversationParticipant::query()
            ->where('conversation_id', $conversationId)
            ->where('user_id', $request->user()->id)
            ->whereNull('left_at')
            ->exists();

        abort_unless($authorized, 403, 'You are not allowed to access this attachment.');

        $diskName = (string) config('messaging.attachments.disk', 'local');
        $disk = Storage::disk($diskName);

        return new StreamedResponse(function () use ($disk, $attachment): void {
            echo $disk->get($attachment->storage_path);
        }, 200, [
            'Content-Type' => $attachment->mime,
            'Content-Disposition' => 'inline; filename="' . addslashes($attachment->original_name) . '"',
            'Content-Length' => (string) $attachment->size_bytes,
        ]);
    }
}
