<?php

namespace Tests\Feature;

use App\Domains\AI\Models\AiKnowledgeSnippet;
use App\Domains\Identity\Actions\RegisterTenantAction;
use App\Models\User;
use Database\Seeders\PermissionSeeder;
use Database\Seeders\PlanSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Tests\TestCase;

class AiReplySuggestionTest extends TestCase
{
    use RefreshDatabase;

    public function test_owner_can_generate_a_reply_suggestion_and_it_is_logged(): void
    {
        $this->seed([
            PlanSeeder::class,
            PermissionSeeder::class,
        ]);

        /** @var User $user */
        $user = app(RegisterTenantAction::class)->execute([
            'company_name' => 'Luna Store',
            'full_name' => 'Maya Haddad',
            'email' => 'maya@example.com',
            'password' => 'Password123!',
            'country' => 'LB',
            'phone' => '+96170001122',
        ]);

        AiKnowledgeSnippet::query()->create([
            'tenant_id' => $user->tenant_id,
            'type' => 'shipping_policy',
            'title' => 'Standard Shipping',
            'content_text' => 'Delivery takes 2 to 4 business days inside Beirut.',
            'language_code' => 'en',
            'status' => 'active',
        ]);

        $conversationId = (string) Str::uuid();

        $response = $this->actingAs($user)->postJson("/api/ai/conversations/{$conversationId}/suggest-reply", [
            'latest_customer_message' => 'Hi, what is the price and do you deliver?',
            'language' => 'en',
            'recent_history' => [
                'Customer asked about a perfume set.',
            ],
            'relevant_products' => [
                [
                    'name' => 'Rose Perfume Set',
                    'price' => '$35',
                ],
            ],
        ]);

        $response->assertOk()
            ->assertJsonPath('data.human_approval_required', true)
            ->assertJsonPath('data.detected_intent', 'ask_price');

        $this->assertDatabaseHas('ai_interactions', [
            'tenant_id' => $user->tenant_id,
            'user_id' => $user->id,
            'conversation_id' => $conversationId,
            'feature_key' => 'reply_suggestion',
        ]);

        $this->assertDatabaseHas('ai_usage_daily', [
            'tenant_id' => $user->tenant_id,
            'feature_key' => 'reply_suggestion',
            'requests_count' => 1,
        ]);
    }
}
