<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class CreditTransaction extends Model
{
    protected $keyType = 'string';
    public $incrementing = false;

    protected $fillable = [
        'user_id',
        'amount',
        'type',
        'description',
        'reference_id',
        'reference_type',
        'created_by',
    ];

    protected $casts = [
        'amount' => 'integer',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (!$model->id) {
                $model->id = (string) Str::uuid();
            }
        });
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    // ── Factory-Methoden ──────────────────────────────────────────────

    public static function onboarding(User $user, int $amount = 300): self
    {
        return self::create([
            'user_id'     => $user->id,
            'amount'      => $amount,
            'type'        => 'onboarding',
            'description' => 'Willkommens-Bonus bei Registrierung',
        ]);
    }

    public static function affiliate(User $user, int $amount, string $referredUserName, string $referralId): self
    {
        return self::create([
            'user_id'        => $user->id,
            'amount'         => $amount,
            'type'           => 'affiliate',
            'description'    => "Referral-Bonus: {$referredUserName} ist seit 3 Monaten aktiv",
            'reference_id'   => $referralId,
            'reference_type' => 'affiliate_referral',
        ]);
    }

    public static function adminGift(User $user, int $amount, string $reason, User $admin): self
    {
        return self::create([
            'user_id'     => $user->id,
            'amount'      => $amount,
            'type'        => 'admin_gift',
            'description' => "Admin-Geschenk: {$reason}",
            'created_by'  => $admin->id,
        ]);
    }

    public static function refund(User $user, int $amount, string $reason, string $logId, User $admin): self
    {
        return self::create([
            'user_id'        => $user->id,
            'amount'         => $amount,
            'type'           => 'refund',
            'description'    => "Rückerstattung: {$reason}",
            'reference_id'   => $logId,
            'reference_type' => 'agent_log',
            'created_by'     => $admin->id,
        ]);
    }
}
