<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\ConversationResource;
use App\Http\Resources\MessageResource;
use App\Http\Resources\PropertyProposalResource;
use App\Models\Conversation;
use App\Models\Message;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ConversationController extends Controller
{
    /**
     * § 13.6 — affichage messagerie (conversation + messages).
     */
    public function show(Request $request, Conversation $conversation): JsonResponse
    {
        $this->authorize('view', $conversation);

        $user = $request->user();

        $conversation->load([
            'messages' => static fn ($q) => $q->orderBy('id'),
            'proposal.photos',
            'proposal.city',
        ]);

        Message::query()
            ->where('conversation_id', $conversation->id)
            ->whereNull('read_at')
            ->where('sender_id', '!=', $user->id)
            ->update(['read_at' => now()]);

        $conversation->load([
            'messages' => static fn ($q) => $q->orderBy('id'),
            'proposal.photos',
            'proposal.city',
        ]);

        return response()->json([
            'data' => [
                'conversation' => (new ConversationResource($conversation))->resolve(),
                'proposal' => $conversation->proposal !== null
                    ? (new PropertyProposalResource($conversation->proposal))->resolve()
                    : null,
                'messages' => MessageResource::collection($conversation->messages)->resolve(),
            ],
        ]);
    }
}
