<?php

namespace Tests\Unit\Services\Payments;

use App\Services\EmailService;
use App\Services\Payments\PaymentTestNotificationService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Mockery;
use Tests\TestCase;

class PaymentTestNotificationServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_send_logs_and_sends_email(): void
    {
        DB::table('configuration')->insert([
            ['config_key' => 'school_year', 'config_value' => '2024-2025'],
            ['config_key' => 'installment_date', 'config_value' => '2025-06-01'],
        ]);

        DB::table('users')->insert([
            ['id' => 10, 'firstname' => 'Primary', 'lastname' => 'Parent', 'email' => 'primary@example.com', 'status' => 'Active'],
            ['id' => 11, 'firstname' => 'Secondary', 'lastname' => 'Parent', 'email' => 'secondary@example.com', 'status' => 'Active'],
        ]);

        DB::table('families')->insert([
            'id' => 1,
            'family_code' => 'FAM-1',
            'is_active' => 1,
        ]);

        DB::table('family_guardians')->insert([
            [
                'family_id' => 1,
                'user_id' => 10,
                'relation' => 'guardian',
                'is_primary' => 1,
                'receive_emails' => 1,
                'receive_sms' => 0,
            ],
            [
                'family_id' => 1,
                'user_id' => 11,
                'relation' => 'guardian',
                'is_primary' => 0,
                'receive_emails' => 1,
                'receive_sms' => 0,
            ],
        ]);

        DB::table('invoices')->insert([
            'id' => 1,
            'parent_id' => 10,
            'invoice_number' => 'INV-1',
            'total_amount' => 200.00,
            'balance' => 150.00,
            'paid_amount' => 50.00,
            'status' => 'Partially Paid',
            'school_year' => '2024-2025',
            'semester' => 'Spring',
            'issue_date' => '2025-01-01',
        ]);

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

        $service = new PaymentTestNotificationService($email);
        $result = $service->send('primary@example.com', 'no_payment');

        $this->assertTrue($result['ok']);
        $this->assertDatabaseHas('payment_notification_logs', [
            'parent_id' => 10,
            'type' => 'no_payment',
            'to_email' => 'primary@example.com',
        ]);
    }
}
