<?php

declare(strict_types=1);

use App\Models\Deal;
use App\Models\Project;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;

uses(DatabaseTransactions::class);

beforeEach(function () {
    $this->tenant = Tenant::factory()->create();
    $this->user = User::factory()->for($this->tenant)->create();
    $this->actingAs($this->user);
    DB::statement('SET app.current_tenant_id = '.$this->tenant->id);
    $this->project = Project::factory()->for($this->tenant)->create();
    Deal::factory()->count(3)->for($this->tenant)->for($this->project)->create();
});

it('pd exported on deals CSV export', function () {
    $r = $this->post('/api/deals/export', ['format' => 'csv']);
    $r->assertStatus(200);
    $pd = DB::table('pd_processing_log')->where('action', 'exported')->latest('id')->first();
    expect($pd)->not->toBeNull()
        ->and($pd->subject_type)->toBe('lead')
        ->and($pd->subject_id)->toBeNull()
        ->and($pd->purpose)->toBe('deals_export_csv')
        ->and((int) $pd->actor_tenant_user_id)->toBe($this->user->id);
});

it('pd exported with xlsx purpose', function () {
    $r = $this->post('/api/deals/export', ['format' => 'xlsx']);
    $r->assertStatus(200);
    $pd = DB::table('pd_processing_log')->where('action', 'exported')->latest('id')->first();
    expect($pd)->not->toBeNull()
        ->and($pd->subject_type)->toBe('lead')
        ->and($pd->subject_id)->toBeNull()
        ->and($pd->purpose)->toBe('deals_export_xlsx')
        ->and((int) $pd->actor_tenant_user_id)->toBe($this->user->id);
});
