<?php

namespace App\Services\Meet;

use App\Models\DirectConversation;
use App\Models\DirectMessage;
use App\Models\DirectParticipant;
use App\Models\Organization;
use App\Models\User;

class DirectMessageService
{
    public function findOrCreateDm(User $user, Organization $organization, string $otherUserRef): DirectConversation
    {
        $ownerRef = $user->ownerRef();
        $userRef = $ownerRef;

        $existing = DirectConversation::owned($ownerRef)
            ->where('organization_id', $organization->id)
            ->where('type', 'dm')
            ->whereHas('participants', fn ($q) => $q->where('user_ref', $userRef))
            ->whereHas('participants', fn ($q) => $q->where('user_ref', $otherUserRef))
            ->first();

        if ($existing) {
            return $existing;
        }

        $conversation = DirectConversation::create([
            'owner_ref' => $ownerRef,
            'organization_id' => $organization->id,
            'type' => 'dm',
        ]);

        foreach ([$userRef, $otherUserRef] as $ref) {
            DirectParticipant::create([
                'conversation_id' => $conversation->id,
                'user_ref' => $ref,
            ]);
        }

        return $conversation;
    }

    public function postMessage(DirectConversation $conversation, User $user, string $body, ?int $parentId = null): DirectMessage
    {
        abort_unless(
            $conversation->participants()->where('user_ref', $user->ownerRef())->exists(),
            403,
        );

        return DirectMessage::create([
            'owner_ref' => $conversation->owner_ref,
            'conversation_id' => $conversation->id,
            'sender_ref' => $user->ownerRef(),
            'sender_name' => $user->name,
            'body' => trim($body),
            'parent_id' => $parentId,
        ]);
    }
}
