<?php

declare(strict_types=1);

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

/**
 * Create plans table for subscription tiers.
 *
 * Plans define the limits and features available to each company
 * based on their subscription level.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('plans', function (Blueprint $table) {
            $table->id();

            // ═══════════════════════════════════════════════════════════════════════
            // PLAN IDENTIFICATION
            // ═══════════════════════════════════════════════════════════════════════
            $table->string('name', 100)
                ->comment('Display name: Básico, Profesional, Enterprise');

            $table->string('slug', 50)->unique()
                ->comment('URL-safe identifier: basic, professional, enterprise');

            $table->text('description')->nullable()
                ->comment('Plan description for marketing');

            // ═══════════════════════════════════════════════════════════════════════
            // PRICING
            // ═══════════════════════════════════════════════════════════════════════
            $table->decimal('price', 12, 2)->default(0.00)
                ->comment('Monthly price');

            $table->decimal('annual_price', 12, 2)->nullable()
                ->comment('Annual price (if different from monthly * 12)');

            $table->enum('billing_cycle', ['monthly', 'annual', 'lifetime'])
                ->default('monthly')
                ->comment('Billing frequency');

            $table->string('currency_code', 3)->default('COP')
                ->comment('ISO 4217 currency code');

            // ═══════════════════════════════════════════════════════════════════════
            // LIMITS
            // ═══════════════════════════════════════════════════════════════════════
            $table->unsignedInteger('max_users')->default(5)
                ->comment('Maximum users allowed (0 = unlimited)');

            $table->unsignedInteger('max_collectors')->default(3)
                ->comment('Maximum collector users allowed');

            $table->unsignedInteger('max_active_credits')->default(100)
                ->comment('Maximum concurrent active credits');

            $table->decimal('max_monthly_volume', 15, 2)->default(50000000.00)
                ->comment('Maximum monthly disbursement volume');

            $table->unsignedInteger('max_clients')->default(500)
                ->comment('Maximum client records');

            // ═══════════════════════════════════════════════════════════════════════
            // FEATURES (flags)
            // ═══════════════════════════════════════════════════════════════════════
            $table->json('features')->nullable()
                ->comment('Feature flags: {"pwa": true, "api_access": false, "reports": true}');

            $table->boolean('has_pwa_access')->default(true)
                ->comment('Can use PWA for collectors');

            $table->boolean('has_api_access')->default(false)
                ->comment('Can use external API');

            $table->boolean('has_advanced_reports')->default(false)
                ->comment('Access to advanced reporting');

            $table->boolean('has_multi_branch')->default(false)
                ->comment('Can create multiple branches');

            $table->boolean('has_custom_branding')->default(false)
                ->comment('Can customize logo and colors');

            $table->boolean('has_priority_support')->default(false)
                ->comment('Priority support access');

            // ═══════════════════════════════════════════════════════════════════════
            // STATUS & DISPLAY
            // ═══════════════════════════════════════════════════════════════════════
            $table->boolean('is_active')->default(true)
                ->comment('Plan available for new subscriptions');

            $table->boolean('is_public')->default(true)
                ->comment('Show on public pricing page');

            $table->boolean('is_trial_available')->default(true)
                ->comment('Offer trial period for this plan');

            $table->unsignedInteger('trial_days')->default(14)
                ->comment('Trial period duration in days');

            $table->unsignedSmallInteger('sort_order')->default(0)
                ->comment('Display order on pricing page');

            // ═══════════════════════════════════════════════════════════════════════
            // METADATA
            // ═══════════════════════════════════════════════════════════════════════
            $table->string('badge_text', 50)->nullable()
                ->comment('Badge text: "Más Popular", "Mejor Valor"');

            $table->string('badge_color', 20)->nullable()
                ->comment('Badge color: primary, success, warning');

            $table->timestamps();
            $table->softDeletes();

            // ═══════════════════════════════════════════════════════════════════════
            // INDEXES
            // ═══════════════════════════════════════════════════════════════════════
            $table->index('is_active');
            $table->index('is_public');
            $table->index('sort_order');
        });

        // ═══════════════════════════════════════════════════════════════════════════
        // SEED DEFAULT PLANS
        // ═══════════════════════════════════════════════════════════════════════════
        $this->seedDefaultPlans();
    }

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

    /**
     * Seed default subscription plans.
     */
    private function seedDefaultPlans(): void
    {
        $plans = [
            [
                'name' => 'Básico',
                'slug' => 'basic',
                'description' => 'Ideal para emprendedores y pequeños prestamistas',
                'price' => 99000.00,
                'annual_price' => 999000.00,
                'max_users' => 2,
                'max_collectors' => 1,
                'max_active_credits' => 50,
                'max_monthly_volume' => 20000000.00,
                'max_clients' => 100,
                'has_pwa_access' => true,
                'has_api_access' => false,
                'has_advanced_reports' => false,
                'has_multi_branch' => false,
                'has_custom_branding' => false,
                'has_priority_support' => false,
                'features' => json_encode(['sms_notifications' => false, 'email_notifications' => true]),
                'sort_order' => 1,
            ],
            [
                'name' => 'Profesional',
                'slug' => 'professional',
                'description' => 'Para empresas de microcrédito en crecimiento',
                'price' => 249000.00,
                'annual_price' => 2490000.00,
                'max_users' => 10,
                'max_collectors' => 5,
                'max_active_credits' => 200,
                'max_monthly_volume' => 100000000.00,
                'max_clients' => 500,
                'has_pwa_access' => true,
                'has_api_access' => false,
                'has_advanced_reports' => true,
                'has_multi_branch' => false,
                'has_custom_branding' => true,
                'has_priority_support' => false,
                'features' => json_encode(['sms_notifications' => true, 'email_notifications' => true]),
                'badge_text' => 'Más Popular',
                'badge_color' => 'primary',
                'sort_order' => 2,
            ],
            [
                'name' => 'Enterprise',
                'slug' => 'enterprise',
                'description' => 'Solución completa para operaciones a gran escala',
                'price' => 599000.00,
                'annual_price' => 5990000.00,
                'max_users' => 0, // unlimited
                'max_collectors' => 0, // unlimited
                'max_active_credits' => 0, // unlimited
                'max_monthly_volume' => 0.00, // unlimited
                'max_clients' => 0, // unlimited
                'has_pwa_access' => true,
                'has_api_access' => true,
                'has_advanced_reports' => true,
                'has_multi_branch' => true,
                'has_custom_branding' => true,
                'has_priority_support' => true,
                'features' => json_encode([
                    'sms_notifications' => true,
                    'email_notifications' => true,
                    'whatsapp_notifications' => true,
                    'custom_integrations' => true,
                ]),
                'badge_text' => 'Todo Incluido',
                'badge_color' => 'warning',
                'sort_order' => 3,
            ],
        ];

        foreach ($plans as $plan) {
            DB::table('plans')->insert(array_merge($plan, [
                'created_at' => now(),
                'updated_at' => now(),
            ]));
        }
    }
};
