<?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;
use Illuminate\Support\Facades\Storage;

final class StreamerUpload extends Model
{
    use HasFactory;

    protected $fillable = [
        'streamer_id',
        'image_path',
        'status',
        'gold_reward',
        'admin_notes',
        'approved_by',
        'approved_at',
        'discord_message_id',
    ];

    protected $casts = [
        'gold_reward' => 'integer',
        'approved_at' => 'datetime',
    ];

    /**
     * Get the streamer that owns the upload.
     */
    public function streamer(): BelongsTo
    {
        return $this->belongsTo(Streamer::class);
    }

    /**
     * Get the admin who approved/rejected the upload.
     */
    public function approvedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'approved_by', 'ID');
    }

    /**
     * Get the full URL for the uploaded image.
     */
    public function getImageUrlAttribute(): string
    {
        return Storage::url($this->image_path);
    }

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

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

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

    /**
     * Approve the upload and award gold to streamer.
     */
    public function approve(int $goldReward, int $adminUserId): void
    {
        $this->update([
            'status' => 'approved',
            'gold_reward' => $goldReward,
            'approved_by' => $adminUserId,
            'approved_at' => now(),
        ]);

        // Award gold to streamer
        if ($this->streamer && $this->streamer->user) {
            $this->streamer->user->increment('gold', $goldReward);
            $this->streamer->increment('total_gold_earned', $goldReward);
        }
    }

    /**
     * Reject the upload.
     */
    public function reject(int $adminUserId, ?string $notes = null): void
    {
        $this->update([
            'status' => 'rejected',
            'admin_notes' => $notes,
            'approved_by' => $adminUserId,
            'approved_at' => now(),
        ]);
    }

    /**
     * Delete the upload and its associated file.
     */
    public function deleteWithFile(): bool
    {
        // Delete the file from storage
        if (Storage::exists($this->image_path)) {
            Storage::delete($this->image_path);
        }

        return $this->delete();
    }
}
