<?php

namespace App\Services\CreditScore\Components;

use App\Services\CreditScore\ComponentResult;

class ConductFlagsComponent
{
    public function calculate(array $data): ComponentResult
    {
        $activeBlacklist = (bool) ($data['active_blacklist'] ?? false);
        $activeWatchlist = (bool) ($data['active_watchlist'] ?? false);
        $seriousCollectionEscalations = max(0, (int) ($data['serious_collection_escalations'] ?? 0));
        $unresolvedControlFlags = max(0, (int) ($data['unresolved_control_flags'] ?? 0));

        $score = 100;
        if ($activeBlacklist) {
            $score -= 70;
        }
        if ($activeWatchlist) {
            $score -= 20;
        }
        $score -= min(30, $seriousCollectionEscalations * 10);
        $score -= min(50, $unresolvedControlFlags * 25);
        $score = max(0, min(100, $score));

        $positive = [];
        $negative = [];
        if (! $activeBlacklist && ! $activeWatchlist && $seriousCollectionEscalations === 0 && $unresolvedControlFlags === 0) {
            $positive[] = 'No active conduct or control flags are recorded.';
        }
        if ($activeBlacklist) {
            $negative[] = 'An active blacklist record requires manual credit review.';
        }
        if ($activeWatchlist) {
            $negative[] = 'An active watchlist record is present.';
        }
        if ($seriousCollectionEscalations > 0) {
            $negative[] = "{$seriousCollectionEscalations} serious collection escalation(s) are recorded.";
        }
        if ($unresolvedControlFlags > 0) {
            $negative[] = "{$unresolvedControlFlags} unresolved control flag(s) are recorded.";
        }

        return new ComponentResult(
            'conduct_flags',
            $score,
            true,
            [
                'active_blacklist' => $activeBlacklist,
                'active_watchlist' => $activeWatchlist,
                'serious_collection_escalations' => $seriousCollectionEscalations,
                'unresolved_control_flags' => $unresolvedControlFlags,
            ],
            $positive,
            $negative,
        );
    }
}
