<?php

namespace App\Console\Commands;

use App\Models\Client;
use App\Services\Operations\ClientHealthScoreService;
use Illuminate\Console\Command;

class HealthScoreCommand extends Command
{
    protected $signature = 'dw:health-scores {client? : Belirli müşteri ID} {--platform=} {--status=active} {--save : Sonucu client_health_scores tablosuna kaydet}';

    protected $description = 'Müşteri sağlık skorlarını hesaplar ve isteğe bağlı olarak günlük snapshot kaydeder.';

    public function handle(ClientHealthScoreService $healthScores): int
    {
        $clientId = $this->argument('client');

        if ($clientId) {
            $client = Client::find($clientId);

            if (! $client) {
                $this->error('Müşteri bulunamadı: '.$clientId);
                return self::FAILURE;
            }

            $card = $healthScores->calculate($client);
            $this->line($client->company_name.' → '.$card['score'].'/100 · '.$card['status_label']);

            foreach (array_slice($card['risk_items'], 0, 5) as $risk) {
                $this->line(' - ['.($risk['priority'] ?? 'medium').'] '.$risk['title']);
            }

            if ($this->option('save')) {
                $healthScores->calculateAndStore($client);
                $this->info('Günlük sağlık skoru kaydedildi.');
            }

            return self::SUCCESS;
        }

        $filters = [
            'platform' => $this->option('platform'),
            'status' => $this->option('status'),
        ];

        if ($this->option('save')) {
            $result = $healthScores->storeAll($filters);
            $this->info($result['message']);
            return self::SUCCESS;
        }

        $data = $healthScores->dashboard($filters);
        $this->info('Müşteri sağlık skoru özeti');
        $this->line('Toplam müşteri: '.$data['summary']['clients_total']);
        $this->line('Ortalama skor: '.$data['summary']['average_score']);
        $this->line('Kritik/Riskli: '.($data['summary']['critical'] + $data['summary']['risk']));

        $this->newLine();
        $this->table(
            ['Müşteri', 'Skor', 'Durum', 'Risk'],
            $data['clients']->map(fn (array $card) => [
                $card['client']->company_name,
                $card['score'],
                $card['status_label'],
                count($card['risk_items']),
            ])->all()
        );

        return self::SUCCESS;
    }
}
