<?php

use App\Models\Permission;
use App\Models\Role;
use App\Models\User;

function grantReportPerms(User $user)
{
    $role = Role::create(['name' => 'Reporter', 'slug' => 'reporter']);
    $view = Permission::firstOrCreate(['slug' => 'reports-view'], ['name' => 'Reports View']);
    $exp = Permission::firstOrCreate(['slug' => 'reports-export'], ['name' => 'Reports Export']);
    $role->permissions()->syncWithoutDetaching([$view->id, $exp->id]);
    $role->users()->syncWithoutDetaching($user->id);
}

it('exports CSV with headings', function (): void {
    $user = User::factory()->create();
    grantReportPerms($user);
    $this->actingAs($user);

    $response = $this->get(route('reports.export', ['slug' => 'field-jobs-completed', 'format' => 'csv']));
    $response->assertOk();
    $ctype = $response->headers->get('Content-Type');
    expect($ctype)->toStartWith('text/csv');
    $content = $response->getContent();
    expect($content)->toStartWith('#,Pogodba,Terenski,Zaklju');
});

it('exports PDF', function (): void {
    $user = User::factory()->create();
    grantReportPerms($user);
    $this->actingAs($user);

    $response = $this->get(route('reports.export', ['slug' => 'field-jobs-completed', 'format' => 'pdf']));
    $response->assertOk();
    $response->assertHeader('Content-Type');
    $ctype = $response->headers->get('Content-Type');
    expect($ctype)->toContain('application/pdf');
});

it('exports XLSX', function (): void {
    $user = User::factory()->create();
    grantReportPerms($user);
    $this->actingAs($user);

    $response = $this->get(route('reports.export', ['slug' => 'field-jobs-completed', 'format' => 'xlsx']));
    $response->assertOk();
    $ctype = $response->headers->get('Content-Type');
    expect($ctype)->toContain('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
});
