<?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
    {
        Schema::create('cashback_wallets', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->unique()->constrained()->cascadeOnDelete();
            $table->decimal('balance', 14, 2)->default(0);
            $table->timestamps();
        });

        Schema::create('cashback_ledgers', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->enum('entry_type', ['credit', 'debit']);
            $table->decimal('amount', 14, 2);
            $table->string('reference', 191)->unique();
            $table->enum('source', ['reward', 'purchase', 'refund', 'admin_adjust']);
            $table->string('narration');
            $table->json('meta_json')->nullable();
            $table->decimal('balance_before', 14, 2);
            $table->decimal('balance_after', 14, 2);
            $table->timestamp('created_at')->useCurrent();

            $table->index(['user_id', 'created_at']);
            $table->index(['source', 'entry_type']);
        });
    }

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

