<?php

namespace Tests\Feature;

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

class AdminProductsBatchReturnUrlSanitizeTest extends TestCase
{
    use RefreshDatabase;

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

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

    public function test_admin_products_batch_redirects_to_default_when_return_url_has_nested_back(): void
    {
        $this->loginAsPlatformAdmin();

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

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

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

    public function test_admin_products_batch_redirects_to_default_when_return_url_contains_quotes(): void
    {
        $this->loginAsPlatformAdmin();

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

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

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

    public function test_admin_products_batch_keeps_return_url_when_safe(): void
    {
        $this->loginAsPlatformAdmin();

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

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

        $response->assertRedirect('/admin/products?status=published&merchant_id=1');
    }
}
