<?php

declare(strict_types=1);

use App\Mail\ImportCompletedNotification;
use App\Models\ImportLog;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;

uses(DatabaseTransactions::class);

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

test('письмо об успешном импорте содержит счётчики', function (): void {
    $log = ImportLog::factory()->create([
        'tenant_id' => $this->tenant->id,
        'user_id' => $this->user->id,
        'status' => 'done',
        'rows_added' => 120,
        'rows_updated' => 8,
        'rows_skipped' => 2,
    ]);

    $rendered = (new ImportCompletedNotification($log, 'done'))->render();

    expect($rendered)->toContain('120')
        ->and($rendered)->toContain('Импорт завершён');
});

test('письмо о неуспешном импорте сообщает об ошибке', function (): void {
    $log = ImportLog::factory()->create([
        'tenant_id' => $this->tenant->id,
        'user_id' => $this->user->id,
        'status' => 'failed',
        'error_message' => 'Файл повреждён',
    ]);

    $mailable = new ImportCompletedNotification($log, 'failed');
    $rendered = $mailable->render();

    expect($rendered)->toContain('Файл повреждён')
        ->and($mailable->envelope()->subject)->toContain('не удался');
});
