<?php

namespace App\Http\Controllers\API\Investor;

use App\Http\Controllers\API\BaseApiController;
use App\Models\Message;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class MessageController extends BaseApiController
{
    public function index(Request $request): JsonResponse
    {
        $messages = Message::where('receiver_id', $request->user()->id)
            ->orWhere('sender_id', $request->user()->id)
            ->with(['sender:id,uid,name,email', 'receiver:id,uid,name,email'])
            ->orderByDesc('created_at')
            ->paginate(20);

        return $this->paginatedResponse($messages);
    }

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'receiver_id' => 'nullable|exists:users,id',
            'subject'     => 'required|string|max:255',
            'body'        => 'required|string|max:5000',
            'priority'    => 'in:normal,importante,urgente',
            'proposal_id' => 'nullable|exists:investment_proposals,id',
        ]);

        // Default receiver to main admin (GCRPE) when not specified
        $receiverId = $request->receiver_id
            ?? User::role('admin')->first()?->id
            ?? User::role('super_admin')->first()?->id;

        if (!$receiverId) {
            return $this->errorResponse('Não foi possível determinar o destinatário.', 422);
        }

        $message = Message::create([
            ...$request->only(['subject', 'body', 'proposal_id']),
            'receiver_id' => $receiverId,
            'sender_id'   => $request->user()->id,
            'priority'    => $request->priority ?? 'normal',
        ]);

        return $this->successResponse($message->load(['sender:id,name', 'receiver:id,name']), 'Mensagem enviada', 201);
    }

    public function show(Request $request, int $id): JsonResponse
    {
        $message = Message::where(fn($q) =>
            $q->where('receiver_id', $request->user()->id)
              ->orWhere('sender_id', $request->user()->id)
        )->with(['sender:id,uid,name,email', 'receiver:id,uid,name,email'])->findOrFail($id);

        return $this->successResponse($message);
    }

    public function markAsRead(Request $request, int $id): JsonResponse
    {
        $message = Message::where('receiver_id', $request->user()->id)->findOrFail($id);
        $message->update(['is_read' => true, 'read_at' => now()]);
        return $this->successResponse(null, 'Mensagem marcada como lida');
    }
}
