<?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('subscriptions', function (Blueprint $table) {

            // ── Primary Key ───────────────────────────────────────────────────
            $table->id('subscription_id');

            // ── Relationships ─────────────────────────────────────────────────
            $table->foreignId('customer_id')
                  ->constrained('easypaisa_customers', 'customer_id')
                  ->onDelete('restrict')
                  ->comment('Subscribing customer');

            $table->foreignId('plan_id')
                  ->constrained('plans', 'plan_id')
                  ->onDelete('restrict')
                  ->comment('Plan this subscription belongs to');

            $table->foreignId('product_id')
                  ->constrained('products', 'product_id')
                  ->onDelete('restrict')
                  ->comment('Product/variant selected');

            // ── Plan / Product Snapshot (immutable at time of purchase) ───────
            $table->string('variant', 20)->comment('Variant snapshot: platinum/gold/silver/bronze');
            $table->string('plan_eful_code', 50)->nullable()->comment('EFUL plan code at time of subscription');
            $table->string('efu_product_name', 150)->nullable()->comment('EFU product name at time of subscription');

            // ── Certificate / Policy ──────────────────────────────────────────
            $table->string('cert_id', 100)->nullable()->unique()->comment('Certificate ID issued by EFU after activation');
            $table->string('reference_id', 100)->unique()->comment('Unique internal reference for this subscription');
            $table->string('policy_number', 100)->nullable()->unique()->comment('EFU policy number after activation');

            // ── Payment / Transaction ─────────────────────────────────────────
            $table->string('transaction_id', 150)->nullable()->unique()->comment('Easypaisa payment transaction ID');
            $table->string('payment_order_id', 150)->nullable()->unique()->comment('Easypaisa paymentOrderID sent to createPayment');
            $table->string('payment_order_title', 200)->nullable()->comment('Title sent to Easypaisa createPayment');

            // ── Premium / Pricing ─────────────────────────────────────────────
            $table->decimal('premium', 12, 2)->comment('Annual premium amount in PKR');
            $table->decimal('premium_paisa', 12, 0)->nullable()->comment('Premium in paisa (premium * 100), sent to Easypaisa');
            $table->string('currency', 10)->default('PKR');
            $table->string('contribution_age_group', 100)->nullable()->comment('Age bracket used for pricing e.g. 18-45 years');

            // ── Policy Status ─────────────────────────────────────────────────
            $table->enum('policy_status', [
                'pending_payment',   // Created, waiting for payment
                'active',            // Payment confirmed, policy active
                'expired',           // Past expiry date
                'cancelled',         // Cancelled by customer or admin
                'failed',            // Payment failed
                'grace_period',      // Within grace period after expiry
                'suspended',         // Suspended by admin
            ])->default('pending_payment');

            // ── Dates ─────────────────────────────────────────────────────────
            $table->timestamp('subscription_timestamp')->useCurrent()->comment('When subscription was created');
            $table->date('coverage_start_date')->nullable()->comment('Policy coverage start date (set on activation)');
            $table->date('coverage_end_date')->nullable()->comment('Policy coverage end date / expiry');
            $table->date('expiry_date')->nullable()->comment('Same as coverage_end_date, explicit expiry');
            $table->integer('grace_period_days')->default(30)->comment('Grace period in days after expiry');
            $table->date('grace_period_end_date')->nullable()->comment('Grace period end date (expiry + grace_period_days)');

            // ── Activation ────────────────────────────────────────────────────
            $table->timestamp('activated_at')->nullable()->comment('When payment was confirmed and policy activated');
            $table->timestamp('cancelled_at')->nullable();
            $table->string('cancellation_reason', 500)->nullable();

            // ── EFU API Response Snapshots ────────────────────────────────────
            $table->json('payment_response')->nullable()->comment('Raw Easypaisa createPayment response');
            $table->json('activation_response')->nullable()->comment('Raw Easypaisa/EFU activation response');

            // ── Renewal ───────────────────────────────────────────────────────
            $table->boolean('is_renewal')->default(false);
            $table->foreignId('renewed_from_subscription_id')
                  ->nullable()
                  ->constrained('subscriptions', 'subscription_id')
                  ->nullOnDelete()
                  ->comment('Previous subscription this was renewed from');

            // ── Soft Delete & Timestamps ──────────────────────────────────────
            $table->softDeletes();
            $table->timestamps();

            // ── Indexes ───────────────────────────────────────────────────────
            $table->index('policy_status');
            $table->index('customer_id');
            $table->index('expiry_date');
            $table->index('coverage_start_date');
            $table->index(['customer_id', 'policy_status']);
        });
    }

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