<?php

namespace App\Console\Commands;

use App\Models\AffiliateCreditLog;
use App\Models\AffiliateReferral;
use App\Models\CreditTransaction;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;

class ProcessAffiliateQualifications extends Command
{
    protected $signature = 'affiliates:process-qualifications';
    protected $description = 'Schreibt Credits für qualifizierte Referrals gut';

    const CREDITS_PER_REFERRAL = 500;

    public function handle(): void
    {
        $qualified = AffiliateReferral::where('status', 'pending')
            ->where('qualifies_at', '<=', now())
            ->with(['affiliate.user', 'referredUser'])
            ->get();

        foreach ($qualified as $referral) {
            $referredUser = $referral->referredUser;
            if (!$referredUser || $referredUser->status->value !== 'active') {
                $referral->update(['status' => 'cancelled']);
                continue;
            }

            $affiliate = $referral->affiliate;
            $credits = self::CREDITS_PER_REFERRAL;

            // Credits via Transaktion gutschreiben
            CreditTransaction::affiliate(
                $affiliate->user,
                $credits,
                $referredUser->name,
                $referral->id
            );

            // Log erstellen
            AffiliateCreditLog::create([
                'affiliate_id' => $affiliate->id,
                'referral_id'  => $referral->id,
                'credits'      => $credits,
                'reason'       => '3-Monats-Qualifikation: ' . $referredUser->name,
            ]);

            // Referral als bezahlt markieren
            $referral->update([
                'status'          => 'paid',
                'paid_at'         => now(),
                'credits_awarded' => $credits,
            ]);

            // Affiliate-Stats aktualisieren
            $affiliate->increment('qualified_referrals');
            $affiliate->increment('total_credits_earned', $credits);

            // Benachrichtigung
            try {
                Mail::to($affiliate->user->email)->send(
                    new \App\Mail\AffiliateQualifiedMail(
                        $affiliate->user,
                        $referredUser,
                        $credits
                    )
                );
            } catch (\Throwable $e) {
                report($e);
            }

            $this->info("{$credits} Credits an {$affiliate->user->name} für Referral {$referredUser->name}");
        }

        $this->info("{$qualified->count()} Referrals verarbeitet.");
    }
}
