<?php

use App\Enums\CampaignStatus;
use App\Models\Ad;
use App\Models\Group;
use App\Models\Kategori;

use function Pest\Laravel\actingAs;

beforeEach(function () {
    Group::firstOrCreate(['name' => Group::ADMIN]);
    Group::firstOrCreate(['name' => Group::MEMBERS]);
});

test('admin dashboard shows aggregate stats', function () {
    $admin = makeAdmin();
    $kategori = Kategori::factory()->create();

    Ad::factory()->active()->create(['user_id' => $admin->id, 'klik' => 10]);
    Ad::factory()->create(['user_id' => $admin->id, 'status' => CampaignStatus::Pending]);

    $response = actingAs($admin)->get(route('dashboard'));

    $response->assertOk();
    $stats = $response->inertiaProps()['stats'];

    expect($stats['total_campaigns'])->toBe(2)
        ->and($stats['active_campaigns'])->toBe(1)
        ->and($stats['total_klik'])->toBe(10)
        ->and($stats['credit_balance'])->toBe($admin->credit);
});

test('member dashboard only shows own data', function () {
    $member = makeMemberWithCredit(500);
    $other = makeMember();
    $kategori = Kategori::factory()->create();

    Ad::factory()->active()->create(['user_id' => $member->id, 'klik' => 5]);
    Ad::factory()->active()->create(['user_id' => $other->id, 'klik' => 99]);

    $response = actingAs($member)->get(route('dashboard'));

    $stats = $response->inertiaProps()['stats'];

    expect($stats['total_campaigns'])->toBe(1) // hanya milik member
        ->and($stats['total_klik'])->toBe(5);  // bukan 99 milik other
});

test('dashboard performance chart returns aktif and selesai campaigns sorted by klik desc', function () {
    $admin = makeAdmin();
    $kategori = Kategori::factory()->create();

    Ad::factory()->active()->create(['user_id' => $admin->id, 'judul' => 'A', 'klik' => 5]);
    Ad::factory()->create(['user_id' => $admin->id, 'judul' => 'B', 'klik' => 20, 'status' => CampaignStatus::Selesai]);
    Ad::factory()->create(['user_id' => $admin->id, 'judul' => 'C', 'klik' => 3, 'status' => CampaignStatus::Pending]); // excluded

    $response = actingAs($admin)->get(route('dashboard'));
    $performance = $response->inertiaProps()['performance'];

    expect($performance)->toHaveCount(2)
        ->and($performance[0]['judul'])->toBe('B') // klik tertinggi
        ->and($performance[1]['judul'])->toBe('A');
});
