<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

final class Streamer extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'code',
        'discord_id',
        'channel_link',
        'percentage',
        'total_gold_earned',
        'is_active',
        'status',
        'requested_at',
        'processed_at',
    ];

    protected $casts = [
        'percentage' => 'decimal:2',
        'total_gold_earned' => 'integer',
        'is_active' => 'boolean',
        'requested_at' => 'datetime',
        'processed_at' => 'datetime',
    ];

    /**
     * Get the user that owns the streamer.
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id', 'ID');
    }

    /**
     * Get the uploads for the streamer.
     */
    public function uploads()
    {
        return $this->hasMany(StreamerUpload::class);
    }


    /**
     * Calculate gold reward for streamer based on player's gold amount.
     */
    public function calculateReward(int $playerGold): int
    {
        return (int) floor($playerGold * ($this->percentage / 100));
    }

    /**
     * Add gold to streamer's total earnings and user's gold balance.
     */
    public function addGoldReward(int $goldAmount): void
    {
        $this->increment('total_gold_earned', $goldAmount);
        
        if ($this->user) {
            $this->user->increment('gold', $goldAmount);
        }
    }

    /**
     * Scope to get only active streamers.
     */
    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope to get streamer by code.
     */
    public function scopeByCode(Builder $query, string $code): Builder
    {
        return $query->where('code', strtoupper($code));
    }

    /**
     * Scope to get streamers by status.
     */
    public function scopeByStatus(Builder $query, string $status): Builder
    {
        return $query->where('status', $status);
    }

    /**
     * Scope to get pending requests.
     */
    public function scopePending(Builder $query): Builder
    {
        return $query->where('status', 'pending');
    }

    /**
     * Scope to get approved streamers.
     */
    public function scopeApproved(Builder $query): Builder
    {
        return $query->where('status', 'approved');
    }

    /**
     * Scope to get rejected requests.
     */
    public function scopeRejected(Builder $query): Builder
    {
        return $query->where('status', 'rejected');
    }

    /**
     * Find streamer by code.
     */
    public static function findByCode(string $code): ?self
    {
        return self::where('code', strtoupper($code))->first();
    }
}
