<?php

use App\Models\Ad;
use App\Models\Kategori;
use App\Models\User;

beforeEach(function () {
    $this->admin = User::factory()->create();
    $this->kategori = Kategori::factory()->create();
});

test('rotator selects active ad within time window and with remaining credit', function () {
    attachKategori(Ad::factory()->active()->create([
        'user_id' => $this->admin->id,
    ]), $this->kategori);

    expect(Ad::rotatable($this->kategori->id)->count())->toBe(1);
});

test('pending ad is not rotatable', function () {
    attachKategori(Ad::factory()->create([ // default status Pending
        'user_id' => $this->admin->id,
    ]), $this->kategori);

    expect(Ad::rotatable($this->kategori->id)->count())->toBe(0);
});

test('ad is rotatable regardless of lifetime klik (daily budget model)', function () {
    attachKategori(Ad::factory()->active()->create([
        'user_id' => $this->admin->id,
        'credit' => 100,
        'klik' => 100,
        'budget_harian' => 10000,
    ]), $this->kategori);

    // Model harian: lifetime klik tidak batasi rotator (cap dicegah inline via is_paused).
    expect(Ad::rotatable($this->kategori->id)->count())->toBe(1);
});

test('rotator orders sequentially by id (round-robin)', function () {
    Ad::factory()->active()->create([
        'user_id' => $this->admin->id, 'klik_hari_ini' => 50, 'klik_tanggal' => today(),
    ])->kategoris()->sync($this->kategori);
    Ad::factory()->active()->create([
        'user_id' => $this->admin->id, 'klik_hari_ini' => 5, 'klik_tanggal' => today(),
    ])->kategoris()->sync($this->kategori);
    Ad::factory()->active()->create([
        'user_id' => $this->admin->id, 'klik_hari_ini' => 20, 'klik_tanggal' => today(),
    ])->kategoris()->sync($this->kategori);

    $picked = Ad::rotatable($this->kategori->id)->get();

    // Urutan tetap by id terlepas counter klik harian (pointer kategori yg memilih).
    expect($picked->pluck('id')->all())
        ->toBe($picked->sortBy('id')->pluck('id')->values()->all());
});

test('ad outside time window is not rotatable', function () {
    attachKategori(Ad::factory()->active()->create([
        'user_id' => $this->admin->id,
        'jam_tayang_mulai' => '00:00:00',
        'jam_tayang_selesai' => '00:00:01', // window already passed
    ]), $this->kategori);

    expect(Ad::rotatable($this->kategori->id)->count())->toBe(0);
});
