<?php

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

/**
 * Migration: Create payment_configurations table
 *
 * Stores both MTN MoMo API credentials (Collection & Disbursement) and
 * listing pricing configuration (institution/machine service types).
 * All sensitive credential fields are encrypted using Laravel's encryption.
 *
 * @package PaymentConfigurationModule
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('payment_configurations', function (Blueprint $table) {
            $table->id();

            // ── Service Type (for listing pricing) ──────────────────────────
            $table->enum('service_type', ['institution', 'machine'])
                ->nullable()
                ->comment('Type of listing service; null = global MTN MoMo config');

            // ── Pricing ──────────────────────────────────────────────────────
            $table->boolean('is_free')->default(false);
            $table->decimal('amount_ssp', 15, 2)->default(0)->comment('Price in South Sudan Pounds');
            $table->decimal('amount_usd', 15, 2)->nullable()->comment('Price in US Dollars');
            $table->json('frequencies')->nullable()->comment('Available payment frequencies');
            $table->string('default_frequency', 20)->default('yearly');
            $table->integer('grace_period_days')->default(7);
            $table->text('description')->nullable();

            // ── MTN MoMo Collection API Credentials (encrypted) ─────────────
            $table->text('collection_api_user')->nullable()->comment('Encrypted Collection API User ID');
            $table->text('collection_api_key')->nullable()->comment('Encrypted Collection API Key');
            $table->text('collection_subscription_key')->nullable()->comment('Encrypted Collection Subscription Key');

            // ── MTN MoMo Disbursement API Credentials (encrypted) ───────────
            $table->text('disbursement_api_user')->nullable()->comment('Encrypted Disbursement API User ID');
            $table->text('disbursement_api_key')->nullable()->comment('Encrypted Disbursement API Key');
            $table->text('disbursement_subscription_key')->nullable()->comment('Encrypted Disbursement Subscription Key');

            // ── Environment & Status ─────────────────────────────────────────
            $table->enum('environment', ['sandbox', 'production'])->default('sandbox');
            $table->boolean('is_active')->default(true);

            $table->timestamps();

            $table->index('service_type');
            $table->index('is_active');
            $table->index('environment');
        });
    }

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