<?php

namespace Database\Seeders;

use App\Models\CreditTransaction;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class MigrateBonusCreditsSeeder extends Seeder
{
    public function run(): void
    {
        // Falls bonus_credits Spalte noch existiert → migrieren
        if (Schema::hasColumn('users', 'bonus_credits')) {
            $users = DB::table('users')
                ->where('bonus_credits', '>', 0)
                ->get(['id', 'bonus_credits']);

            foreach ($users as $user) {
                CreditTransaction::create([
                    'user_id'     => $user->id,
                    'amount'      => $user->bonus_credits,
                    'type'        => 'onboarding',
                    'description' => 'Migriert von bonus_credits',
                ]);
            }

            $this->command->info("{$users->count()} User-Credits migriert.");
            return;
        }

        // Spalte bereits entfernt → prüfe ob Transaktionen fehlen
        $usersWithoutTx = DB::table('users')
            ->leftJoin('credit_transactions', 'users.id', '=', 'credit_transactions.user_id')
            ->whereNull('credit_transactions.id')
            ->whereNotNull('users.email_verified_at')
            ->pluck('users.id');

        foreach ($usersWithoutTx as $userId) {
            CreditTransaction::create([
                'user_id'     => $userId,
                'amount'      => 300,
                'type'        => 'onboarding',
                'description' => 'Willkommens-Bonus (nachträglich migriert)',
            ]);
        }

        $this->command->info("{$usersWithoutTx->count()} verifizierte User ohne Transaktionen nachträglich migriert (300 Credits).");
    }
}
