<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use Laravel\Sanctum\Sanctum;

class AuthFlowTest extends TestCase
{
    // We use RefreshDatabase to ensure a clean state, but we need to seed roles
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        // Create specific users for testing to avoid reliance on default seeder
        User::factory()->create([
            'email' => 'admin@test.com',
            'role' => 'ADMIN',
        ]);
        User::factory()->create([
            'email' => 'sales@test.com',
            'role' => 'SALESMAN',
        ]);
    }

    public function test_user_can_login()
    {
        $response = $this->postJson('/api/login', [
            'email' => 'admin@test.com',
            'password' => 'password',
        ]);

        $response->assertStatus(200)
            ->assertJsonStructure(['user']);
    }

    public function test_admin_can_access_protected_supplier_route()
    {
        $admin = User::where('email', 'admin@test.com')->first();

        Sanctum::actingAs($admin, ['*']);

        $response = $this->getJson('/api/suppliers');

        $response->assertStatus(200);
    }

    public function test_salesman_cannot_access_protected_supplier_route()
    {
        $sales = User::where('email', 'sales@test.com')->first();

        Sanctum::actingAs($sales, ['*']);

        $response = $this->getJson('/api/suppliers');

        $response->assertStatus(403);
    }

    public function test_salesman_can_access_sales_route()
    {
        $sales = User::where('email', 'sales@test.com')->first();

        Sanctum::actingAs($sales, ['*']);

        $response = $this->getJson('/api/sales');

        $response->assertStatus(200);
    }
}
