<?php

namespace Tests\Unit\Models;

use App\Models\NotificationLog;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\Feature\Concerns\BuildsFeatureData;
use Tests\TestCase;

class NotificationLogModelTest extends TestCase
{
    use BuildsFeatureData;
    use DatabaseTransactions;

    public function test_scopes_filter_notifications_correctly(): void
    {
        $applicant = $this->createApplicant();
        $job = $this->createJob();
        $application = $this->createJobApplication($applicant, $job);

        $scheduledDue = $this->createNotificationLog($application, [
            'status' => 'scheduled',
            'scheduled_at' => now()->subMinutes(5),
        ]);

        $scheduledFuture = $this->createNotificationLog($application, [
            'status' => 'scheduled',
            'channel' => 'whatsapp',
            'type' => 'stage2_passed',
            'scheduled_at' => now()->addHour(),
        ]);

        $pending = $this->createNotificationLog($application, [
            'status' => 'pending',
            'type' => 'accepted',
            'channel' => 'email',
        ]);

        $sent = $this->createNotificationLog($application, [
            'status' => 'sent',
            'type' => 'rejected',
        ]);

        $scheduledIds = NotificationLog::scheduled()->pluck('id');
        $readyIds = NotificationLog::readyToSend()->pluck('id');
        $pendingOrScheduledIds = NotificationLog::pendingOrScheduled()->pluck('id');

        $this->assertTrue($scheduledIds->contains($scheduledDue->id));
        $this->assertTrue($scheduledIds->contains($scheduledFuture->id));
        $this->assertFalse($scheduledIds->contains($pending->id));

        $this->assertTrue($readyIds->contains($scheduledDue->id));
        $this->assertFalse($readyIds->contains($scheduledFuture->id));

        $this->assertTrue($pendingOrScheduledIds->contains($scheduledDue->id));
        $this->assertTrue($pendingOrScheduledIds->contains($scheduledFuture->id));
        $this->assertTrue($pendingOrScheduledIds->contains($pending->id));
        $this->assertFalse($pendingOrScheduledIds->contains($sent->id));
    }

    public function test_is_cancellable_and_status_label_mapping_work(): void
    {
        $applicant = $this->createApplicant();
        $job = $this->createJob();
        $application = $this->createJobApplication($applicant, $job);

        $log = $this->createNotificationLog($application, [
            'status' => 'scheduled',
        ]);

        $this->assertTrue($log->isCancellable());
        $this->assertSame('Dijadwalkan', $log->status_label);

        $log->update(['status' => 'cancelled']);
        $log->refresh();

        $this->assertFalse($log->isCancellable());
        $this->assertSame('Dibatalkan', $log->status_label);

        $log->update(['status' => 'failed']);
        $log->refresh();
        $this->assertSame('Gagal', $log->status_label);
    }
}
