<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreConversationMessageRequest;
use App\Models\Conversation;
use App\Services\Channels\ChannelMessageSender;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ConversationMessageController extends Controller
{
    public function index(Conversation $conversation, Request $request): JsonResponse
    {
        $user = auth()->user();
        $membership = $user->memberships()->where('organization_id', $conversation->organization_id)->first();
        abort_unless($membership !== null && ($membership->role === 'owner' || $membership->hasPrivilege('view_inbox')), 403);

        $afterId = $request->query('after_id');
        $query = $conversation->messages()->oldest('sent_at')->oldest();

        if ($afterId) {
            $query->where('id', '>', $afterId);
        }

        $messages = $query->get()->map(fn ($message) => [
            'id' => $message->id,
            'sender_type' => $message->sender_type,
            'body' => $message->body,
            'sent_at' => $message->sent_at->timezone('Asia/Dhaka')->format('H:i'),
            'metadata' => $message->metadata,
        ]);

        return response()->json([
            'messages' => $messages,
            'current_page' => $conversation->current_page,
            'status' => $conversation->status,
        ]);
    }

    public function store(StoreConversationMessageRequest $request, Conversation $conversation, ChannelMessageSender $sender)
    {
        $data = $request->validated();

        $metadata = [];
        if (! empty($data['reply_to_message_id'])) {
            $replyMsg = $conversation->messages()->find($data['reply_to_message_id']);
            if ($replyMsg) {
                $metadata['reply_to'] = [
                    'id' => $replyMsg->id,
                    'body' => Str::limit($replyMsg->body, 60),
                ];
            }
        }

        $message = $conversation->messages()->create([
            'sender_type' => 'human',
            'body' => $data['body'],
            'sent_at' => now(),
            'metadata' => empty($metadata) ? null : $metadata,
        ]);

        $message = $sender->send($message);

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => [
                    'id' => $message->id,
                    'sender_type' => $message->sender_type,
                    'body' => $message->body,
                    'sent_at' => $message->sent_at->timezone('Asia/Dhaka')->format('H:i'),
                    'metadata' => $message->metadata,
                    'delivery_status' => $message->delivery_status,
                    'delivery_error' => $message->delivery_error,
                ],
            ]);
        }

        return back()->with('status', 'Reply sent to customer.');
    }
}
