<?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();
    $this->deal = Deal::factory()->for($this->tenant)->for($this->project)->create();
});

it('writes pd_processing_log viewed when deal card opened', function () {
    $this->getJson("/api/deals/{$this->deal->id}")->assertOk();

    $row = DB::table('pd_processing_log')->where('action', 'viewed')->latest('id')->first();
    expect($row)->not->toBeNull()
        ->and($row->subject_type)->toBe('lead')
        ->and((int) $row->subject_id)->toBe($this->deal->id)
        ->and((int) $row->actor_tenant_user_id)->toBe($this->user->id)
        ->and($row->purpose)->toBe('lead_card_view');
});

it('does not write pd_processing_log for 404 lookups', function () {
    $before = DB::table('pd_processing_log')->count();
    $this->getJson('/api/deals/999999')->assertNotFound();
    expect(DB::table('pd_processing_log')->count())->toBe($before);
});
