<?php

namespace App\Console\Commands;

use App\Models\PackagePurchase;
use App\Models\Tenant;
use App\Models\User;
use App\Models\TenantPackage;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

class MigrateLegacyPurchases extends Command
{
    protected $signature = 'packages:migrate-legacy';
    protected $description = 'Migrate legacy purchases to new system with temp tenants';

    public function handle()
    {
        $legacyPurchases = PackagePurchase::whereNull('tenant_id')->get();

        if ($legacyPurchases->isEmpty()) {
            $this->info('No legacy purchases found.');
            return 0;
        }

        $this->info("Found {$legacyPurchases->count()} legacy purchases.");

        foreach ($legacyPurchases as $purchase) {
            if (!$purchase->user_id) {
                // Create temp user if no user
                $tempUser = User::create([
                    'name' => 'Legacy User ' . $purchase->id,
                    'email' => 'legacy' . $purchase->id . '@fotospiel.local',
                    'password' => Hash::make('legacy'),
                    'username' => 'legacy' . $purchase->id,
                    'first_name' => 'Legacy',
                    'last_name' => 'User',
                    'address' => 'Legacy Address',
                    'phone' => '000000000',
                    'email_verified_at' => now(),
                ]);

                $tempTenant = Tenant::create([
                    'user_id' => $tempUser->id,
                    'name' => 'Legacy Tenant ' . $purchase->id,
                    'status' => 'active',
                ]);

                $purchase->update([
                    'user_id' => $tempUser->id,
                    'tenant_id' => $tempTenant->id,
                ]);

                // Assign default free package
                TenantPackage::create([
                    'tenant_id' => $tempTenant->id,
                    'package_id' => 1, // Assume free package ID 1
                    'expires_at' => now()->addYear(),
                    'is_active' => true,
                ]);

                $this->info("Created temp user/tenant for purchase {$purchase->id}");
            } else {
                $user = User::find($purchase->user_id);
                if ($user && $user->tenant) {
                    $purchase->update(['tenant_id' => $user->tenant->id]);
                    $this->info("Assigned tenant for purchase {$purchase->id}");
                } else {
                    $this->error("Could not assign tenant for purchase {$purchase->id}");
                }
            }
        }

        $this->info('Legacy migration completed.');
        return 0;
    }
}