<?php

namespace Tests\Feature;

use App\Enums\CertificateStatus;
use App\Models\CertificateDownload;
use App\Models\Participant;
use App\Models\User;
use App\Services\CertificateDownloadService;
use App\Services\IcNumberService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CertificateDownloadTest extends TestCase
{
    use RefreshDatabase;

    private Participant $participant;

    protected function setUp(): void
    {
        parent::setUp();

        $icService = app(IcNumberService::class);
        $ic = '900101101234';

        $this->participant = Participant::create([
            'full_name' => 'AHMAD BIN ABDULLAH',
            'ic_number' => $icService->encrypt($ic),
            'ic_number_hash' => $icService->hash($ic),
            'imported_by' => User::factory()->create()->id,
            'is_active' => true,
        ]);
    }

    public function test_first_download_is_recorded(): void
    {
        $service = app(CertificateDownloadService::class);
        $service->recordDownload($this->participant, 'participant', 'test.pdf');

        $this->participant->refresh();

        $this->assertEquals(1, $this->participant->download_count);
        $this->assertEquals(CertificateStatus::Downloaded, $this->participant->certificate_status);
        $this->assertNotNull($this->participant->first_downloaded_at);
        $this->assertDatabaseHas('certificate_downloads', [
            'participant_id' => $this->participant->id,
            'download_type' => 'first_download',
        ]);
    }

    public function test_redownload_is_recorded(): void
    {
        $service = app(CertificateDownloadService::class);
        $service->recordDownload($this->participant, 'participant');
        $service->recordDownload($this->participant->fresh(), 'participant');

        $this->participant->refresh();

        $this->assertEquals(2, $this->participant->download_count);
        $this->assertEquals(2, CertificateDownload::count());
        $this->assertDatabaseHas('certificate_downloads', [
            'download_type' => 'redownload',
        ]);
    }

    public function test_unique_participant_download_count(): void
    {
        $service = app(CertificateDownloadService::class);
        $service->recordDownload($this->participant, 'participant');
        $service->recordDownload($this->participant->fresh(), 'participant');
        $service->recordDownload($this->participant->fresh(), 'participant');

        $uniqueDownloaded = Participant::where('certificate_status', CertificateStatus::Downloaded->value)->count();
        $totalTransactions = CertificateDownload::count();

        $this->assertEquals(1, $uniqueDownloaded);
        $this->assertEquals(3, $totalTransactions);
    }

    public function test_download_requires_verified_session(): void
    {
        $this->post('/e-sijil/download')->assertStatus(403);
    }
}
