<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        if (Schema::hasTable('client_health_scores')) {
            return;
        }

        Schema::create('client_health_scores', function (Blueprint $table) {
            $table->id();
            $table->foreignId('client_id')->constrained()->cascadeOnDelete();
            $table->date('score_date')->index();
            $table->unsignedTinyInteger('score')->default(0);
            $table->string('status', 30)->default('watch')->index();
            $table->string('readiness', 30)->nullable()->index();
            $table->unsignedTinyInteger('api_score')->default(0);
            $table->unsignedTinyInteger('data_quality_score')->default(0);
            $table->unsignedTinyInteger('report_score')->default(0);
            $table->unsignedTinyInteger('mail_score')->default(0);
            $table->unsignedTinyInteger('alert_score')->default(0);
            $table->unsignedTinyInteger('task_score')->default(0);
            $table->unsignedTinyInteger('onboarding_score')->default(0);
            $table->json('breakdown')->nullable();
            $table->json('risk_items')->nullable();
            $table->json('recommendations')->nullable();
            $table->timestamp('calculated_at')->nullable();
            $table->timestamps();

            $table->unique(['client_id', 'score_date']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('client_health_scores');
    }
};
