<?php

namespace Tests\Unit\Services\Reimbursements;

use App\Services\Reimbursements\ReimbursementBatchAssignmentService;
use App\Services\Reimbursements\ReimbursementLookupService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class ReimbursementBatchAssignmentServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_assign_and_unassign_batch_item(): void
    {
        DB::table('users')->insert([
            'id' => 1,
            'school_id' => 1,
            'firstname' => 'Admin',
            'lastname' => 'User',
            'cellphone' => '5555555555',
            'email' => 'admin@example.com',
            'address_street' => '123 Main',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'is_verified' => 1,
            'status' => 'Active',
            'is_suspended' => 0,
            'failed_attempts' => 0,
            'password' => bcrypt('secret'),
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        DB::table('reimbursement_batches')->insert([
            'id' => 10,
            'title' => 'Batch 10',
            'status' => 'open',
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'opened_at' => now(),
        ]);

        DB::table('expenses')->insert([
            'id' => 100,
            'category' => 'Expense',
            'amount' => 25.00,
            'date_of_purchase' => '2025-01-01',
            'added_by' => 1,
            'purchased_by' => 1,
            'status' => 'approved',
        ]);

        $service = new ReimbursementBatchAssignmentService(new ReimbursementLookupService());

        $result = $service->updateAssignment(100, 10, 1, null, '2025-2026', 'Fall');
        $this->assertSame(10, $result['batch_id']);

        $this->assertDatabaseHas('reimbursement_batch_items', [
            'batch_id' => 10,
            'expense_id' => 100,
            'admin_id' => 1,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
        ]);

        $service->updateAssignment(100, 0, null, null, '2025-2026', 'Fall');

        $this->assertDatabaseHas('reimbursement_batch_items', [
            'batch_id' => 10,
            'expense_id' => 100,
        ]);

        $this->assertDatabaseMissing('reimbursement_batch_items', [
            'batch_id' => 10,
            'expense_id' => 100,
            'unassigned_at' => null,
        ]);
    }
}
