<?php

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

return new class extends Migration
{
    /**
     * Reestructura al modelo ecommerce de tarjetas coleccionables:
     * - Cada sorteo vende tarjetas numeradas únicas (0 .. total_tickets - 1).
     * - La rareza de cada tarjeta otorga llaves (rarity_config configurable).
     * - Los descuentos por volumen son configurables (discount_tiers).
     * - Las transacciones guardan los números de tarjeta elegidos hasta aprobar el pago.
     */
    public function up(): void
    {
        Schema::table('raffles', function (Blueprint $table) {
            // [{rarity: common, probability: 60, keys: 0}, ...] — probabilidades deben sumar 100
            $table->json('rarity_config')->nullable();
            // [{min_quantity: 5, discount_percent: 5}, ...]
            $table->json('discount_tiers')->nullable();
        });

        Schema::table('transactions', function (Blueprint $table) {
            // Números de tarjeta elegidos por el comprador, pendientes de emisión al aprobar el pago
            $table->json('card_numbers')->nullable();
        });

        Schema::table('action_tickets', function (Blueprint $table) {
            $table->dropUnique(['ticket_number']);
            $table->unique(['raffle_id', 'ticket_number']);
            $table->foreignId('transaction_id')->nullable()->constrained('transactions')->onDelete('set null');
            $table->integer('keys_granted')->default(0);
        });
    }

    public function down(): void
    {
        Schema::table('action_tickets', function (Blueprint $table) {
            $table->dropForeign(['transaction_id']);
            $table->dropColumn(['transaction_id', 'keys_granted']);
            $table->dropUnique(['raffle_id', 'ticket_number']);
            $table->unique('ticket_number');
        });

        Schema::table('transactions', function (Blueprint $table) {
            $table->dropColumn('card_numbers');
        });

        Schema::table('raffles', function (Blueprint $table) {
            $table->dropColumn(['rarity_config', 'discount_tiers']);
        });
    }
};
