<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\CompanySubscriptions;
use App\Models\PaymentProfile;

/**
 * Class BackfillPaymentProfiles
 *
 * This command is used to migrate existing Stripe customer IDs from the
 * legacy `company_subscriptions` table into the new `payment_profiles` table.
 *
 * The `payment_profiles` table is designed to decouple payment provider data
 * (like Stripe customer or account IDs) from internal application logic. This
 * is part of a broader effort to support multiple payment methods (e.g., credit cards, ACH)
 * and payment gateways in the future.
 *
 * Why we use a command (instead of doing this in a migration):
 * - Separation of concerns: migrations should only create/modify schema
 * - Safer for production: no risk of long-running data logic blocking deployment
 * - Repeatable and testable: you can run this manually, log its progress, and validate the results
 *
 * How to run:
 *   php artisan backfill:payment-profiles
 *
 * Notes:
 * - Only subscriptions with a non-null `customer_id` will be processed
 * - Existing records in `payment_profiles` with the same company + customer ID are skipped
 * - Outputs how many new records were created and how many were skipped
 *
 * Usage Example:
 *   php artisan backfill:payment-profiles
 *
 */
class BackfillPaymentProfiles extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'backfill:payment-profiles';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Backfill payment_profiles table from existing company_subscriptions.customer_id values';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $this->info("Starting payment profile backfill...");

        $subscriptions = CompanySubscriptions::whereNotNull('customer_id')->get();
        $count = 0;
        $skipped = 0;

        foreach ($subscriptions as $sub) {
            $existing = PaymentProfile::where('provider', 'stripe')
                ->where('provider_customer_id', $sub->customer_id)
                ->where('company_id', $sub->company_id)
                ->first();

            if ($existing) {
                $skipped++;
                continue;
            }

            PaymentProfile::create([
                'company_id' => $sub->company_id,
                'provider' => 'stripe',
                'provider_customer_id' => $sub->customer_id,
                'provider_account_id' => null,
                'metadata' => null,
            ]);

            $count++;
        }

        $this->info("✅ Backfill complete: $count created, $skipped skipped (already exists).");
    }
}
