<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class Affiliate extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'referral_code',
        'status',
        'commission_type',
        'commission_rate',
        'recurring_commissions',
        'minimum_payout',
        'total_earned',
        'total_paid',
        'pending_balance',
        'approved_at',
    ];

    protected function casts(): array
    {
        return [
            'commission_rate' => 'decimal:2',
            'minimum_payout' => 'decimal:2',
            'total_earned' => 'decimal:2',
            'total_paid' => 'decimal:2',
            'pending_balance' => 'decimal:2',
            'recurring_commissions' => 'boolean',
            'approved_at' => 'datetime',
        ];
    }

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

    public function referrals(): HasMany
    {
        return $this->hasMany(AffiliateReferral::class);
    }

    public function commissions(): HasMany
    {
        return $this->hasMany(AffiliateCommission::class);
    }

    public function payouts(): HasMany
    {
        return $this->hasMany(AffiliatePayout::class);
    }

    public static function generateReferralCode(): string
    {
        do {
            $code = Str::lower(Str::random(8));
        } while (self::where('referral_code', $code)->exists());

        return $code;
    }

    public function referralUrl(): string
    {
        $marketingDomain = config('app.domains.marketing');

        return 'https://'.$marketingDomain.'?ref='.$this->referral_code;
    }
}
