<?php

namespace App\Services\CreditScore\Components;

use App\Services\CreditScore\ComponentResult;

class ProfileCompletenessComponent
{
    public function calculate(array $data): ComponentResult
    {
        $checks = [
            'occupation_or_business_present' => (bool) ($data['occupation_or_business_present'] ?? false),
            'monthly_income_present' => (bool) ($data['monthly_income_present'] ?? false),
            'address_present' => (bool) ($data['address_present'] ?? false),
            'primary_next_of_kin_present' => (bool) ($data['primary_next_of_kin_present'] ?? false),
            'required_documents_complete' => (bool) ($data['required_documents_complete'] ?? false),
        ];

        $guarantorRequired = (bool) ($data['guarantor_required'] ?? false);
        if ($guarantorRequired) {
            $checks['active_guarantor_present'] = (bool) ($data['active_guarantor_present'] ?? false);
        }

        $completed = count(array_filter($checks));
        $total = count($checks);
        $score = $total > 0 ? ($completed / $total) * 100 : 100;

        $positive = [];
        $negative = [];
        if ($score >= 80) {
            $positive[] = 'Credit-relevant customer information is substantially complete.';
        }
        if ($score < 60) {
            $negative[] = 'Several credit-relevant profile fields or required documents are incomplete.';
        }

        return new ComponentResult(
            'profile_completeness',
            $score,
            true,
            [
                'checks' => $checks,
                'completed_checks' => $completed,
                'total_checks' => $total,
                'guarantor_required' => $guarantorRequired,
            ],
            $positive,
            $negative,
        );
    }
}
