<?php

namespace App\Http\Controllers\Api\Inbox;

use App\Domains\Conversations\Models\Conversation;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Gate;

class ConversationIndexController extends Controller
{
    public function __invoke(): JsonResponse
    {
        $user = request()->user();
        $tenantId = $user->tenant_id;

        $query = Conversation::query()
            ->with(['contact', 'messages', 'notes.author'])
            ->where('tenant_id', $tenantId)
            ->orderByDesc('last_message_at');

        if (! $user->can('conversations.view_all') && $user->can('conversations.view_assigned')) {
            $query->where('assigned_user_id', $user->id);
        }

        $conversations = $query
            ->get()
            ->map(function (Conversation $conversation) {
                $latestMessage = $conversation->messages->last();

                return [
                    'id' => $conversation->id,
                    'contactId' => $conversation->contact_id,
                    'customerName' => $conversation->contact?->primary_name,
                    'customerPhone' => $conversation->contact?->whatsapp_phone,
                    'customerEmail' => $conversation->contact?->email,
                    'channel' => str($conversation->channel_type)->replace('_', ' ')->title()->value(),
                    'status' => $conversation->status,
                    'priority' => $conversation->priority,
                    'unreadCount' => $conversation->unread_count,
                    'leadTemperature' => match ($conversation->priority) {
                        'urgent', 'high' => 'hot',
                        'medium' => 'warm',
                        default => 'cold',
                    },
                    'location' => $conversation->contact?->city ?? 'Unknown',
                    'summary' => $latestMessage?->body_text ?? 'No messages yet.',
                    'messages' => $conversation->messages->map(fn ($message) => [
                        'id' => $message->id,
                        'sender' => $message->direction === 'outbound' ? 'agent' : 'customer',
                        'text' => $message->body_text,
                        'time' => optional($message->created_at)->format('M d, H:i') ?? 'Now',
                    ])->values()->all(),
                    'notes' => $conversation->notes->map(fn ($note) => [
                        'id' => $note->id,
                        'body' => $note->body,
                        'author' => $note->author?->full_name ?? 'Team member',
                        'time' => optional($note->created_at)->format('M d, H:i') ?? 'Now',
                    ])->values()->all(),
                    'productName' => $this->guessProductName($conversation),
                    'productPrice' => $this->guessProductPrice($conversation),
                    'contactTags' => $this->contactTags($conversation),
                ];
            })
            ->values();

        return response()->json([
            'data' => $conversations,
        ]);
    }

    protected function guessProductName(Conversation $conversation): ?string
    {
        $body = strtolower((string) optional($conversation->messages->last())->body_text);

        return match (true) {
            str_contains($body, 'perfume') => 'Rose Perfume Set',
            str_contains($body, 'bag') => 'Urban Leather Bag',
            default => null,
        };
    }

    protected function guessProductPrice(Conversation $conversation): ?string
    {
        return match ($this->guessProductName($conversation)) {
            'Rose Perfume Set' => '$35',
            'Urban Leather Bag' => '$90',
            default => null,
        };
    }

    protected function contactTags(Conversation $conversation): array
    {
        $body = strtolower((string) optional($conversation->messages->last())->body_text);

        return array_values(array_filter([
            str_contains($body, 'wholesale') ? 'wholesale' : null,
            str_contains($body, 'deliver') || str_contains($body, 'delivery') ? 'delivery_question' : null,
            str_contains($body, 'price') ? 'price_question' : null,
            str_contains($body, 'available') ? 'stock_check' : null,
        ]));
    }
}
