<?php

namespace App\Http\Controllers\Api\Contacts;

use App\Domains\Contacts\Models\Contact;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;

class ContactIndexController extends Controller
{
    public function __invoke(): JsonResponse
    {
        $contacts = Contact::query()
            ->with(['owner', 'conversations.messages'])
            ->where('tenant_id', request()->user()->tenant_id)
            ->orderByDesc('updated_at')
            ->get()
            ->map(function (Contact $contact) {
                $latestConversation = $contact->conversations->sortByDesc('last_message_at')->first();
                $latestMessage = $latestConversation?->messages->last();

                return [
                    'id' => $contact->id,
                    'name' => $contact->primary_name,
                    'phone' => $contact->whatsapp_phone,
                    'instagramHandle' => $contact->instagram_handle,
                    'source' => $contact->source_platform ? str($contact->source_platform)->replace('_', ' ')->title()->value() : 'Manual',
                    'owner' => $contact->owner?->full_name ?? 'Unassigned',
                    'city' => $contact->city,
                    'lastInteraction' => $latestMessage?->created_at?->format('M d, H:i') ?? 'No activity',
                    'conversationCount' => $contact->conversations->count(),
                    'latestSummary' => $latestMessage?->body_text ?? 'No messages yet.',
                ];
            })
            ->values();

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