<?php

namespace Tests\Feature;

use App\Models\Department;
use App\Models\Position;
use App\Models\PositionAuthorityLog;
use App\Models\PositionDutyLog;
use App\Models\User;
use App\Models\UserPosition;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class DutyHallControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_can_view_duty_hall_roster_tab()
    {
        $user = User::factory()->create();

        $department = Department::create(['name' => 'Support', 'rank' => 1]);
        $position = Position::create(['name' => 'Helper', 'department_id' => $department->id, 'rank' => 1, 'type' => 'temp']);

        UserPosition::create([
            'user_id' => $user->id,
            'position_id' => $position->id,
            'status' => 'active',
            'appointed_at' => now(),
        ]);

        $response = $this->actingAs($user)->get(route('duty-hall.index', ['tab' => 'roster']));

        $response->assertStatus(200);
        $response->assertViewIs('duty-hall.index');
        $response->assertViewHas('tab', 'roster');

        $currentStaff = $response->viewData('currentStaff');
        $this->assertNotNull($currentStaff);
        $this->assertEquals(1, $currentStaff->count());
        $this->assertEquals('Support', $currentStaff->first()->name);
    }

    public function test_can_view_duty_hall_leaderboard_tabs()
    {
        $user = User::factory()->create();

        PositionDutyLog::create([
            'user_id' => $user->id,
            'position_id' => 1,
            'login_at' => now()->subMinutes(30),
            'logout_at' => now(),
            'duration_seconds' => 1800,
        ]);

        PositionAuthorityLog::create([
            'user_id' => $user->id,        // operator
            'target_user_id' => $user->id, // target
            'action_type' => 'reward',
            'amount' => 500,
        ]);

        $tabs = ['day', 'week', 'month', 'all'];

        foreach ($tabs as $tab) {
            $response = $this->actingAs($user)->get(route('duty-hall.index', ['tab' => $tab]));

            $response->assertStatus(200);
            $response->assertViewIs('duty-hall.index');
            $response->assertViewHas('tab', $tab);

            $leaderboard = $response->viewData('leaderboard');
            $this->assertNotNull($leaderboard);

            if ($leaderboard->count() > 0) {
                $row = $leaderboard->first();
                $this->assertEquals($user->id, $row->user_id);
                $this->assertEquals(1800, $row->total_seconds);
                $this->assertEquals(1, $row->reward_count);
                $this->assertEquals(500, $row->reward_total);
            }
        }
    }
}
