<?php

namespace Tests\Unit\Services\Payments;

use App\Services\EmailService;
use App\Services\Notifications\UserNotificationDispatchService;
use App\Services\Payments\PaymentMissedCheckService;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Mockery;
use Tests\TestCase;

class PaymentMissedCheckServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_find_users_with_missed_payments(): void
    {
        Carbon::setTestNow(Carbon::parse('2025-03-01'));

        DB::table('users')->insert([
            'id' => 1,
            'firstname' => 'Parent',
            'lastname' => 'Late',
            'cellphone' => '5551112222',
            'email' => 'late@example.com',
            'address_street' => '123 Main',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'password' => bcrypt('secret'),
            'semester' => 'Spring',
            'school_year' => '2024-2025',
            'status' => 'Active',
        ]);

        DB::table('invoices')->insert([
            'id' => 1,
            'parent_id' => 1,
            'invoice_number' => 'INV-1',
            'total_amount' => 100,
            'balance' => 50,
            'paid_amount' => 50,
            'status' => 'Unpaid',
            'school_year' => '2024-2025',
            'semester' => 'Spring',
            'issue_date' => '2025-01-01',
            'due_date' => '2025-02-01',
        ]);

        $service = new PaymentMissedCheckService(
            Mockery::mock(UserNotificationDispatchService::class),
            Mockery::mock(EmailService::class)
        );

        $users = $service->findUsersWithMissedPayments();

        $this->assertCount(1, $users);
        $this->assertSame(1, (int) $users[0]['user_id']);
    }

    public function test_send_reminders_sends_email_and_notification(): void
    {
        $notifier = Mockery::mock(UserNotificationDispatchService::class);
        $notifier->shouldReceive('notifyUser')->once();

        $email = Mockery::mock(EmailService::class);
        $email->shouldReceive('send')->once()->andReturn(true);

        $service = new PaymentMissedCheckService($notifier, $email);

        $result = $service->sendReminders([
            [
                'user_id' => 5,
                'firstname' => 'Parent',
                'lastname' => 'User',
                'email' => 'parent@example.com',
            ],
        ]);

        $this->assertSame(1, $result['sent']);
        $this->assertSame(0, $result['failed']);
    }
}
