<?php

namespace Tests\Feature\Auth;

use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Tests\TestCase;

class GoogleTokenExchangeControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_replaces_the_active_user_cart_with_the_guest_cart_on_google_exchange(): void
    {
        $tenant = $this->createTenant('acme');
        $user = User::factory()->create();
        $catalogItem = $this->createCatalogItem($tenant);
        $userCart = Cart::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'user_id' => $user->id,
            'status' => 'active',
        ]);
        $guestCart = Cart::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'guest_token' => 'google-guest-token',
            'status' => 'active',
        ]);
        $guestCart->items()->create([
            'catalog_item_id' => $catalogItem->id,
            'variant_id' => null,
            'cantidad' => 1,
        ]);

        $exchangeCode = (string) Str::uuid();
        Cache::put("google-oauth-exchange:{$exchangeCode}", [
            'user_id' => $user->id,
            'token' => 'google-access-token',
            'tenant_codigo' => $tenant->codigo,
        ], now()->addMinutes(5));

        $this->withCookie('guest_token', 'google-guest-token')
            ->postJson('/api/auth/google/exchange', [
                'oauth_code' => $exchangeCode,
                'tenant_codigo' => $tenant->codigo,
            ])
            ->assertOk()
            ->assertJsonPath('token', 'google-access-token')
            ->assertCookieExpired('guest_token');

        $this->assertSoftDeleted('carritos', [
            'id' => $userCart->id,
            'status' => 'converted',
        ]);
        $this->assertDatabaseHas('carritos', [
            'id' => $guestCart->id,
            'user_id' => $user->id,
            'guest_token' => null,
            'status' => 'active',
        ]);
    }

    private function createCatalogItem(Tenant $tenant): CatalogItem
    {
        $inventory = Inventory::query()->create(['real_stock' => 10]);

        return CatalogItem::query()->create([
            'tenant_code' => $tenant->codigo,
            'inventory_id' => $inventory->id,
            'slug' => 'google-login-item-'.$tenant->codigo,
            'nombre' => 'Google login item',
            'precio' => '10.00',
            'inventory_policy' => InventoryPolicy::Tracked,
        ]);
    }

    private function createTenant(string $code): Tenant
    {
        $headerLogo = $this->createAttachment("{$code}-header");
        $footerLogo = $this->createAttachment("{$code}-footer");

        return Tenant::query()->create([
            'codigo' => $code,
            'nombre' => ucfirst($code),
            'dominio' => "{$code}.local",
            'primary_color' => '#000000',
            'secondary_color' => '#000000',
            'danger_color' => '#000000',
            'success_color' => '#000000',
            'header_bg_color' => '#000000',
            'footer_bg_color' => '#000000',
            'header_logo_id' => $headerLogo->id,
            'footer_logo_id' => $footerLogo->id,
        ]);
    }

    private function createAttachment(string $name): Attachment
    {
        return Attachment::query()->create([
            'path' => "test/{$name}.png",
            'filename' => "{$name}.png",
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
    }
}
