<?php

namespace App\Services\Engagement;

use App\Models\Conversation;
use App\Models\ConversationMessage;
use App\Modules\Users\Models\User;

/**
 * ربط محادثات AI مع جداول conversations / conversation_messages.
 */
final class ConversationSyncService
{
    public function sync(User $user, ?int $conversationId, string $userPrompt, string $assistantText): int
    {
        $conversation = $this->resolveConversation($user, $conversationId, $userPrompt);

        ConversationMessage::query()->create([
            'conversation_id' => $conversation->id,
            'role' => 'user',
            'content' => $userPrompt,
        ]);

        ConversationMessage::query()->create([
            'conversation_id' => $conversation->id,
            'role' => 'assistant',
            'content' => $assistantText,
        ]);

        $conversation->last_message_at = now();
        if ($conversation->title === 'محادثة جديدة') {
            $conversation->title = \Illuminate\Support\Str::limit(trim($userPrompt), 60);
        }
        $conversation->save();

        return (int) $conversation->id;
    }

    private function resolveConversation(User $user, ?int $conversationId, string $userPrompt): Conversation
    {
        if ($conversationId !== null) {
            $c = Conversation::query()
                ->where('user_id', $user->id)
                ->whereKey($conversationId)
                ->first();
            if ($c !== null) {
                return $c;
            }
        }

        return Conversation::query()->create([
            'user_id' => $user->id,
            'title' => \Illuminate\Support\Str::limit(trim($userPrompt), 60) ?: 'محادثة جديدة',
            'last_message_at' => now(),
        ]);
    }
}
