<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class SecurityTest extends TestCase
{
    use RefreshDatabase;

    public function test_razorpay_webhook_requires_valid_signature()
    {
        $payload = json_encode(['event' => 'payment.captured']);
        
        // Test without signature
        $response = $this->postJson('/api/webhooks/razorpay', json_decode($payload, true));
        $response->assertStatus(401);

        // Test with invalid signature
        $response = $this->postJson('/api/webhooks/razorpay', json_decode($payload, true), [
            'X-Razorpay-Signature' => 'invalid-signature'
        ]);
        $response->assertStatus(401);
    }

    public function test_admin_routes_require_authentication()
    {
        // Test admin dashboard without auth
        $response = $this->get('/admin');
        $response->assertRedirect('/login');

        // Test admin product creation without auth
        $response = $this->post('/admin/products', [
            'name' => 'Test Product',
            'category_id' => 1,
            'price' => 100
        ]);
        $response->assertRedirect('/login');
    }

    public function test_admin_routes_require_proper_role()
    {
        // Create regular user
        $user = User::factory()->create();
        
        // Test admin access with regular user
        $response = $this->actingAs($user)->get('/admin');
        $response->assertStatus(403);
    }

    public function test_input_validation_prevents_xss()
    {
        $admin = User::factory()->create();
        $admin->assignRole('admin');

        // Test XSS in product name
        $response = $this->actingAs($admin)->post('/admin/products', [
            'name' => '<script>alert("xss")</script>',
            'category_id' => 1,
            'price' => 100,
            'opening_stock' => 10
        ]);
        
        $response->assertSessionHasErrors('name');
    }

    public function test_sql_injection_prevention()
    {
        $admin = User::factory()->create();
        $admin->assignRole('admin');

        // Test SQL injection in search
        $response = $this->actingAs($admin)->get('/admin/products?search=\'; DROP TABLE products; --');
        
        // Should not cause error and should return normally
        $response->assertStatus(200);
    }

    public function test_csrf_protection_on_forms()
    {
        $admin = User::factory()->create();
        $admin->assignRole('admin');

        // Test POST without CSRF token
        $response = $this->post('/admin/products', [
            'name' => 'Test Product',
            'category_id' => 1,
            'price' => 100,
            'opening_stock' => 10
        ]);
        
        $response->assertStatus(419); // CSRF token mismatch
    }
}