<?php

namespace App\Http\Controllers;

use App\Models\Campaign;
use App\Models\Contact;
use App\Models\ContactList;
use App\Models\Tag;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    private const LIMIT = 5;

    public function index(Request $request): JsonResponse
    {
        $q = trim((string) $request->input('q', ''));

        if (mb_strlen($q) < 2) {
            return response()->json(['campaigns' => [], 'contacts' => [], 'lists' => [], 'tags' => []]);
        }

        $campaigns = Campaign::where('title', 'like', "%{$q}%")
            ->orderByDesc('updated_at')
            ->limit(self::LIMIT)
            ->get(['id', 'title', 'status', 'type'])
            ->map(fn ($c) => ['id' => $c->id, 'title' => $c->title, 'status' => $c->status, 'type' => $c->type]);

        $contacts = Contact::where(function ($query) use ($q) {
                $query->where('email', 'like', "%{$q}%")
                    ->orWhere('first_name', 'like', "%{$q}%")
                    ->orWhere('last_name', 'like', "%{$q}%");
            })
            ->orderByDesc('updated_at')
            ->limit(self::LIMIT)
            ->get(['id', 'email', 'first_name', 'last_name'])
            ->map(fn ($c) => [
                'id'    => $c->id,
                'email' => $c->email,
                'name'  => trim(($c->first_name ?? '') . ' ' . ($c->last_name ?? '')),
            ]);

        $lists = ContactList::where('title', 'like', "%{$q}%")
            ->limit(self::LIMIT)
            ->get(['id', 'title'])
            ->map(fn ($l) => ['id' => $l->id, 'title' => $l->title]);

        $tags = Tag::where('title', 'like', "%{$q}%")
            ->limit(self::LIMIT)
            ->get(['id', 'title'])
            ->map(fn ($t) => ['id' => $t->id, 'title' => $t->title]);

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