<?php

namespace App\Services\Meet;

use App\Models\ChannelMessage;
use App\Models\DirectMessage;
use App\Models\Organization;
use Illuminate\Support\Collection;

class WorkspaceSearchService
{
    public function search(Organization $organization, string $ownerRef, string $query, int $limit = 20): array
    {
        $term = trim($query);
        if ($term === '') {
            return ['channels' => [], 'messages' => []];
        }

        $like = '%'.$term.'%';

        $channelMessages = ChannelMessage::owned($ownerRef)
            ->whereHas('channel', fn ($q) => $q->where('organization_id', $organization->id))
            ->where('body', 'like', $like)
            ->orderByDesc('created_at')
            ->limit($limit)
            ->with('channel:id,uuid,name')
            ->get()
            ->map(fn (ChannelMessage $m) => [
                'type' => 'channel',
                'uuid' => $m->uuid,
                'body' => $m->body,
                'channel' => $m->channel?->name,
                'channel_uuid' => $m->channel?->uuid,
                'created_at' => $m->created_at?->toIso8601String(),
            ]);

        $directMessages = DirectMessage::owned($ownerRef)
            ->whereHas('conversation', fn ($q) => $q->where('organization_id', $organization->id))
            ->where('body', 'like', $like)
            ->orderByDesc('created_at')
            ->limit($limit)
            ->with('conversation:id,uuid')
            ->get()
            ->map(fn (DirectMessage $m) => [
                'type' => 'dm',
                'uuid' => $m->uuid,
                'body' => $m->body,
                'conversation_uuid' => $m->conversation?->uuid,
                'created_at' => $m->created_at?->toIso8601String(),
            ]);

        return [
            'messages' => $channelMessages->merge($directMessages)->sortByDesc('created_at')->values()->take($limit)->all(),
        ];
    }
}
