<?php

namespace Tests\Feature;

use App\Models\Brand;
use App\Models\Category;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class ECommerceSecurityTest extends TestCase
{
    use RefreshDatabase;

    /**
     * Test guest redirection to login on protected admin routes.
     */
    public function test_guest_unauthorized_access_redirection(): void
    {
        $this->get(route('admin.dashboard'))->assertRedirect('/admin/login');
        $this->get(route('admin.products.index'))->assertRedirect('/admin/login');
    }

    /**
     * Test protected user API routes without auth token return 401 unauthenticated.
     */
    public function test_unauthenticated_api_request(): void
    {
        $this->getJson('/api/v1/auth/user')->assertStatus(401);
        $this->postJson('/api/v1/auth/orders', [])->assertStatus(401);
        $this->getJson('/api/v1/auth/cart')->assertStatus(401);
    }

    /**
     * Test forbidden action with insufficient permission modules.
     */
    public function test_forbidden_module_access(): void
    {
        $staffUser = User::factory()->create([
            'role' => 'admin',
            'permissions' => ['products'], // Only has product module permission
        ]);

        // Dashboard is forbidden
        $this->actingAs($staffUser)->get(route('admin.dashboard'))->assertForbidden();
        
        // Orders is forbidden
        $this->actingAs($staffUser)->get(route('admin.orders.index'))->assertForbidden();
    }

    /**
     * Test file-upload validation.
     */
    public function test_logo_file_upload_validation(): void
    {
        $admin = User::factory()->create(['role' => 'admin', 'permissions' => null]);
        
        Storage::fake('public');

        // 1. Submit an invalid text file disguised as logo image
        $invalidFile = UploadedFile::fake()->create('document.txt', 150, 'text/plain');

        $response = $this->actingAs($admin)->post(route('admin.brands.store'), [
            'name' => 'Text brand',
            'logo_upload' => $invalidFile,
        ]);

        $response->assertSessionHasErrors(['logo_upload']);
        $this->assertDatabaseMissing('brands', ['name' => 'Text brand']);
    }
}
