<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Enums\PriceSyncTaskStatus;
use App\Models\BasicBasketProduct;
use App\Models\PriceSyncRun;
use App\Models\PriceSyncTask;
use App\Models\Store;
use App\Models\StoreProductTarget;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class PriceSyncDispatchTest extends TestCase
{
    use RefreshDatabase;

    public function test_dispatch_command_creates_run_and_submitted_task(): void
    {
        config()->set('dataforseo.enabled', true);
        config()->set('dataforseo.base_url', 'https://api.dataforseo.test');
        config()->set('dataforseo.merchant_google_products.task_post_endpoint', '/v3/merchant/google/products/task_post');
        config()->set('dataforseo.login', 'login');
        config()->set('dataforseo.password', 'password');
        config()->set('dataforseo.batch_size', 100);
        config()->set('dataforseo.max_tasks_per_run', 300);

        Http::fake([
            'https://api.dataforseo.test/v3/merchant/google/products/task_post' => Http::response([
                'status_code' => 20000,
                'tasks' => [[
                    'id' => 'dfs-task-1',
                    'status_code' => 20000,
                    'status_message' => 'Ok.',
                ]],
            ]),
        ]);

        $product = BasicBasketProduct::factory()->create([
            'slug' => 'tortilla-maiz-kilo',
            'name' => 'Tortilla de maíz por kilo',
        ]);
        $store = Store::factory()->create([
            'slug' => 'chedraui',
            'name' => 'Chedraui',
            'domains' => ['chedraui.com.mx'],
            'aliases' => ['Chedraui'],
        ]);
        StoreProductTarget::factory()->create([
            'basic_basket_product_id' => $product->id,
            'store_id' => $store->id,
            'slug' => 'tortilla-maiz-kilo-chedraui',
            'name' => 'Tortilla de maíz por kilo - Chedraui',
            'search_query' => 'chedraui kilo de tortillas de maiz',
            'expected_url' => 'https://www.chedraui.com.mx/tortilla-de-maiz-por-kilo/p',
            'expected_url_contains' => ['chedraui.com.mx', 'tortilla-de-maiz', '/p'],
            'expected_title' => 'Tortilla de maíz por kilo',
            'expected_seller' => 'Chedraui',
            'expected_domain' => 'chedraui.com.mx',
            'required_keywords' => ['tortilla', 'maiz', 'kilo'],
            'negative_keywords' => ['harina'],
        ]);

        $this->artisan('dataforseo:dispatch-tasks --limit=1')
            ->assertExitCode(0);

        $this->assertSame(1, PriceSyncRun::query()->count());
        $this->assertDatabaseHas('price_sync_tasks', [
            'provider_task_id' => 'dfs-task-1',
            'status' => PriceSyncTaskStatus::Submitted->value,
        ]);

        $task = PriceSyncTask::query()->firstOrFail();
        $this->assertSame('chedraui kilo de tortillas de maiz', $task->query);
    }
}
