<?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('site_subscriptions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('merchant_id')->constrained('merchants')->cascadeOnDelete();
            $table->foreignId('plan_id')->nullable()->constrained('plans')->nullOnDelete();
            $table->string('status', 30)->default('pending');
            $table->string('source', 30)->default('manual');
            $table->string('subscription_no', 50)->unique();
            $table->string('plan_name', 100)->nullable();
            $table->string('billing_cycle', 30)->nullable();
            $table->unsignedInteger('period_months')->default(1);
            $table->decimal('amount', 10, 2)->default(0);
            $table->timestamp('starts_at')->nullable();
            $table->timestamp('ends_at')->nullable();
            $table->timestamp('trial_ends_at')->nullable();
            $table->timestamp('activated_at')->nullable();
            $table->timestamp('cancelled_at')->nullable();
            $table->json('snapshot')->nullable();
            $table->json('meta')->nullable();
            $table->timestamps();

            $table->index(['merchant_id', 'status']);
            $table->index(['plan_id', 'status']);
            $table->index('ends_at');
        });
    }

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