<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Api\App\QuickMessageController;
use App\Http\Requests\Api\V1\SendMessageRequest;
use App\Http\Resources\Api\V1\MessageResource;
use App\Models\Message;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Messages — send a single WhatsApp message and read status/history.
 *
 * Reuses the tested single-send pipeline (QuickMessageController →
 * Conversation + Message + WhatsAppDispatcher → workspace engine), wrapping
 * the result in the public { data } envelope.
 */
class MessageController extends V1Controller
{
    /** POST /api/v1/messages — send one message (text / location). */
    public function store(SendMessageRequest $request): JsonResponse
    {
        $type = $request->input('type', 'text');

        // Media single-sends aren't carried by the quick-message pipeline (it
        // only handles text + location). Reject honestly instead of silently
        // shipping a text-only message — point the caller at the right tool.
        if (in_array($type, ['image', 'video', 'document'], true)) {
            return $this->fail(
                'media_unsupported',
                'Media single-sends are not available on /messages yet. Use a media template via /templates + /broadcasts.',
                422
            );
        }

        $params = [
            'to_number'    => $request->input('to'),
            'device_id'    => $request->input('device_id'),
            'message_text' => (string) ($request->input('text') ?? ''),
        ];
        if ($type === 'location') {
            $params['latitude']     = $request->input('latitude');
            $params['longitude']    = $request->input('longitude');
            $params['message_text'] = $params['message_text'] ?: ' ';
        }

        $internal = Request::create('/api/app/send-quick-message', 'POST', $params);
        $internal->setUserResolver(fn () => $request->user());

        // The quick-message controller returns `success` as a human STRING
        // ("Message sent successfully.") on a 200, never boolean true — so the
        // real success signal is the HTTP status + absence of an `error` key.
        $response = app(QuickMessageController::class)->sendQuickMessage($internal);
        $payload  = $response->getData(true);

        if ($response->getStatusCode() >= 300 || isset($payload['error'])) {
            return $this->fail(
                'send_failed',
                $payload['error'] ?? $payload['server_msg'] ?? 'Message could not be sent.',
                $response->getStatusCode() >= 400 ? $response->getStatusCode() : 422
            );
        }

        return $this->created((new MessageResource([
            'id'         => $payload['message_id'] ?? null,
            'to'         => $request->input('to'),
            'type'       => $type,
            'status'     => 'queued',
            'body'       => $request->input('text'),
            'created_at' => now()->toIso8601String(),
        ]))->resolve());
    }

    /** GET /api/v1/messages/{id} — delivery status of one message. */
    public function show(int $id): JsonResponse
    {
        $msg = Message::query()->whereKey($id)
            ->whereHas('conversation', fn ($q) => $q->where('workspace_id', $this->workspaceId()))
            ->first();

        if (!$msg) {
            return $this->fail('not_found', 'Message not found.', 404);
        }

        return $this->ok((new MessageResource($msg))->resolve());
    }

    /** GET /api/v1/messages — recent message history. */
    public function index(Request $request): JsonResponse
    {
        $limit = min(max((int) $request->input('limit', 50), 1), 200);

        $items = Message::query()
            ->whereHas('conversation', fn ($q) => $q->where('workspace_id', $this->workspaceId()))
            ->latest()
            ->limit($limit)
            ->get()
            ->map(fn ($m) => (new MessageResource($m))->resolve())
            ->values();

        return $this->ok($items, ['count' => $items->count()]);
    }
}
