<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;
use App\Models\Club;
use App\Models\Jugador;
use App\Models\AdminUser;
use Illuminate\Support\Facades\Hash;

class JugadorCreationTest extends TestCase
{
    use DatabaseTransactions;

    protected $clubA;
    protected $clubB;

    protected function setUp(): void
    {
        parent::setUp();
        
        $this->clubA = Club::create(['id_club' => 101, 'nombre' => 'Club Alpha']);
        $this->clubB = Club::create(['id_club' => 102, 'nombre' => 'Club Beta']);
    }

    public function test_duplicate_dni_shows_club_name_error()
    {
        // 1. Create an existing player in Club Alpha
        Jugador::create([
            'id_jugador'       => '1019001',
            'documento'        => '99999999',
            'nombre'           => 'Existing',
            'apellido'         => 'Player',
            'fecha_nacimiento' => '1990-01-01',
            'id_club_actual'   => 101,
            'id_club_origen'   => 101,
            'activo'           => 1
        ]);

        // 2. Log in as SuperAdmin (Role 1)
        $this->withSession([
            'admin_logged_in' => true,
            'admin_role'      => 1,
            'admin_username'  => 'supertest'
        ]);

        // 3. Try to create a new player with the same DNI
        $response = $this->post(route('admin.jugadores.store'), [
            'documento'        => '99999999',
            'nombre'           => 'New',
            'apellido'         => 'Player',
            'fecha_nacimiento' => '1995-05-05',
            'id_club_actual'   => 102,
            'id_club_origen'   => 102
        ]);

        // 4. Assert error message contains the club name
        $response->assertSessionHasErrors(['documento']);
        $errors = session('errors')->get('documento');
        $this->assertStringContainsString('Club Alpha', $errors[0]);
    }

    public function test_club_admin_can_see_all_clubs_in_origen()
    {
        // Log in as Club Admin (Role 2)
        $this->withSession([
            'admin_logged_in' => true,
            'admin_role'      => 2,
            'admin_id_club'   => 101,
            'admin_username'  => 'clubadmin'
        ]);

        $response = $this->get(route('admin.jugadores.create'));

        $response->assertStatus(200);
        $response->assertSee('Club Alpha');
        $response->assertSee('Club Beta');
    }
}
