<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('leads', function (Blueprint $table) {
            $table->decimal('original_points', 20, 4)->nullable()->after('points');
            $table->decimal('credited_points', 20, 4)->default(0)->after('original_points');
        });

        DB::statement("UPDATE leads SET original_points = CAST(points AS DECIMAL(20,4)), credited_points = CASE WHEN status = 'approved' AND points_reversed_at IS NULL THEN CAST(points AS DECIMAL(20,4)) ELSE 0 END");

        Schema::create('lead_adjustments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('lead_id')->constrained()->cascadeOnDelete();
            $table->foreignId('admin_id')->nullable()->constrained('users')->nullOnDelete();
            $table->string('token', 190)->unique();
            $table->string('action', 32);
            $table->decimal('points', 20, 4);
            $table->decimal('credited_before', 20, 4);
            $table->decimal('credited_after', 20, 4);
            $table->string('requested_unit', 12)->default('coins');
            $table->decimal('requested_amount', 20, 4)->nullable();
            $table->text('note')->nullable();
            $table->timestamps();

            $table->index(['lead_id', 'created_at']);
        });
    }

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

        Schema::table('leads', function (Blueprint $table) {
            $table->dropColumn(['original_points', 'credited_points']);
        });
    }
};
