<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class MerchantProductsBatchReturnUrlSanitizeTest extends TestCase
{
    use RefreshDatabase;

    protected function loginAsMerchantAdmin(): void
    {
        $this->seed();

        $this->post('/merchant-admin/login', [
            'email' => 'merchant.admin@demo.local',
            'password' => 'Merchant@123456',
        ])->assertRedirect('/merchant-admin');
    }

    public function test_merchant_products_batch_redirects_to_default_when_return_url_has_nested_back(): void
    {
        $this->loginAsMerchantAdmin();

        $product = \App\Models\Product::query()->where('merchant_id', 1)->orderBy('id')->firstOrFail();

        $response = $this->post('/merchant-admin/products/batch', [
            'product_ids' => [$product->id],
            'action' => 'change_status',
            'status' => 'offline',
            'return_url' => '/merchant-admin/products?status=published&back=/merchant-admin',
        ]);

        $response->assertRedirect('/merchant-admin/products');
    }

    public function test_merchant_products_batch_redirects_to_default_when_return_url_contains_quotes(): void
    {
        $this->loginAsMerchantAdmin();

        $product = \App\Models\Product::query()->where('merchant_id', 1)->orderBy('id')->firstOrFail();

        $response = $this->post('/merchant-admin/products/batch', [
            'product_ids' => [$product->id],
            'action' => 'change_status',
            'status' => 'offline',
            'return_url' => '/merchant-admin/products?status=published\'',
        ]);

        $response->assertRedirect('/merchant-admin/products');
    }

    public function test_merchant_products_batch_keeps_return_url_when_safe(): void
    {
        $this->loginAsMerchantAdmin();

        $product = \App\Models\Product::query()->where('merchant_id', 1)->orderBy('id')->firstOrFail();

        $response = $this->post('/merchant-admin/products/batch', [
            'product_ids' => [$product->id],
            'action' => 'change_status',
            'status' => 'offline',
            'return_url' => '/merchant-admin/products?status=published&keyword=SKU',
        ]);

        $response->assertRedirect('/merchant-admin/products?status=published&keyword=SKU');
    }
}
