<?php

namespace App\Http\Controllers\Messenger;

use App\Http\Controllers\Controller;
use App\Http\Requests\Messenger\ReadReceiptRequest;
use App\Models\Messenger\Message;
use App\Services\Messenger\EventDispatcher;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class ReceiptController extends Controller
{
    use AuthorizesRequests;

    public function __construct(
        protected EventDispatcher $eventDispatcher
    ) {}

    public function store(ReadReceiptRequest $request): JsonResponse
    {
        try {
            $data = $request->validated();
            $userId = Auth::id();

            $messages = Message::whereIn('id', $data['message_ids'])
                ->with('conversation')
                ->get();

            $processedCount = 0;

            foreach ($messages as $message) {
                // Check authorization
                if (!$this->authorize('markAsRead', $message)) {
                    continue;
                }

                // Mark receipt
                if ($data['type'] === 'seen') {
                    $message->markAsSeen($userId);
                } else {
                    $message->markAsDelivered($userId);
                }

                $this->eventDispatcher->dispatchMessageReceipt($message, $userId, $data['type']);
                $processedCount++;
            }

            return response()->json([
                'status' => 200,
                'message' => "Marked {$processedCount} messages as {$data['type']}",
                'data' => [
                    'processed_count' => $processedCount,
                    'type' => $data['type'],
                ],
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Failed to mark messages',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
}
