<?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
    {
        if (Schema::hasTable('subscription_payment_methods')) {
            Schema::table('subscription_payment_methods', function (Blueprint $table) {
                $table->unique(['subscriber_type', 'subscriber_id', 'reference'], 'spm_subscriber_ref_unique');
            });

            return;
        }

        Schema::create('subscription_payment_methods', function (Blueprint $table) {
            $table->id();
            $table->morphs('subscriber');
            $table->string('provider');
            $table->string('reference');
            $table->string('brand')->nullable();
            $table->string('last_four', 4)->nullable();
            $table->timestamp('expires_at')->nullable();
            $table->boolean('is_default')->default(false);
            $table->json('meta')->nullable();
            $table->timestamps();
            $table->unique(['subscriber_type', 'subscriber_id', 'reference'], 'spm_subscriber_ref_unique');
        });
    }

    public function down(): void
    {
        Schema::table('subscription_payment_methods', function (Blueprint $table) {
            $table->dropUnique('spm_subscriber_ref_unique');
        });

        Schema::dropIfExists('subscription_payment_methods');
    }
};
