<?php

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('campaign export returns CSV with headers', function () {
    $admin = makeAdmin();
    $kategori = Kategori::factory()->create();

    attachKategori(Ad::factory()->active()->create([
        'user_id' => $admin->id,
        'judul' => 'Iklan Ekspor',
        'klik' => 5,
        'credit' => 100,
    ]), $kategori);

    $response = actingAs($admin)->get(route('campaigns.export'));

    $response->assertOk();
    $response->assertHeader('Content-Type', 'text/csv; charset=UTF-8');

    $content = $response->streamedContent();
    // BOM + header row + 1 data row.
    expect($content)->toContain('Judul')
        ->and($content)->toContain('Iklan Ekspor')
        ->and($content)->toContain('Status');
});

test('member export only includes their own campaigns', function () {
    $member = makeMemberWithCredit(1000);
    $other = makeMember();
    $kategori = Kategori::factory()->create();

    attachKategori(Ad::factory()->create([
        'user_id' => $member->id, 'judul' => 'MILIK_SAYA',
    ]), $kategori);
    attachKategori(Ad::factory()->create([
        'user_id' => $other->id, 'judul' => 'MILIK_ORANG',
    ]), $kategori);

    $response = actingAs($member)->get(route('campaigns.export'));

    $content = $response->streamedContent();
    expect($content)->toContain('MILIK_SAYA')
        ->and($content)->not->toContain('MILIK_ORANG');
});
