<?php

namespace App\Http\Controllers\API\Admin;

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

class AdminMessageController extends BaseApiController
{
    public function index(Request $request): JsonResponse
    {
        $messages = Message::with(['sender:id,uid,name,email', 'receiver:id,uid,name,email'])
            ->when($request->search, fn($q) =>
                $q->where('subject', 'like', "%{$request->search}%"))
            ->orderByDesc('created_at')
            ->paginate(20);

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

    public function show(int $id): JsonResponse
    {
        $message = Message::with(['sender:id,uid,name,email', 'receiver:id,uid,name,email', 'proposal:id,code,name'])->findOrFail($id);
        return $this->successResponse($message);
    }

    public function reply(Request $request, int $id): JsonResponse
    {
        $original = Message::findOrFail($id);
        $request->validate([
            'body'     => 'required|string|max:5000',
            'priority' => 'in:normal,importante,urgente',
        ]);

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

        return $this->successResponse($reply, 'Resposta enviada', 201);
    }

    public function sendBulk(Request $request): JsonResponse
    {
        $request->validate([
            'receiver_ids'   => 'required|array|min:1',
            'receiver_ids.*' => 'exists:users,id',
            'subject'        => 'required|string|max:255',
            'body'           => 'required|string|max:5000',
            'priority'       => 'in:normal,importante,urgente',
        ]);

        foreach ($request->receiver_ids as $receiverId) {
            Message::create([
                'sender_id'   => $request->user()->id,
                'receiver_id' => $receiverId,
                'subject'     => $request->subject,
                'body'        => $request->body,
                'priority'    => $request->priority ?? 'normal',
            ]);
        }

        return $this->successResponse(null, count($request->receiver_ids) . ' mensagens enviadas');
    }
}
