<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Raffle extends Model
{
    protected $fillable = [
        'title',
        'description',
        'commercial_value',
        'fiscal_value',
        'ticket_price',
        'draw_date',
        'total_tickets',
        'sold_tickets',
        'status',
        'type',
        'rules',
        'invoice_path',
        'vehicle_docs_path',
        'marchamo_path',
        'inspection_path',
        'images_json',
        'video_url',
        'winner_user_id',
        'winner_action_ticket_id',
        'rarity_config',
        'discount_tiers',
    ];

    protected $casts = [
        'draw_date' => 'datetime',
        'total_tickets' => 'integer',
        'sold_tickets' => 'integer',
        'commercial_value' => 'decimal:2',
        'fiscal_value' => 'decimal:2',
        'ticket_price' => 'decimal:2',
        'images_json' => 'array',
        'winner_user_id' => 'integer',
        'winner_action_ticket_id' => 'integer',
        'rarity_config' => 'array',
        'discount_tiers' => 'array',
    ];

    /**
     * Configuración de rarezas por defecto: probabilidad (%) y llaves otorgadas.
     * común 68.5% (0 llaves), poco común 21% (0), rara 8% (1),
     * épica 2.5% (1), legendaria 0.5% (1).
     */
    public const DEFAULT_RARITY_CONFIG = [
        ['rarity' => 'common', 'probability' => 68.5, 'keys' => 0],
        ['rarity' => 'uncommon', 'probability' => 21, 'keys' => 0],
        ['rarity' => 'rare', 'probability' => 8, 'keys' => 1],
        ['rarity' => 'epic', 'probability' => 2.5, 'keys' => 1],
        ['rarity' => 'legendary', 'probability' => 0.5, 'keys' => 1],
    ];

    public function effectiveRarityConfig(): array
    {
        $config = $this->rarity_config;

        return (is_array($config) && count($config) > 0) ? $config : self::DEFAULT_RARITY_CONFIG;
    }

    public function effectiveDiscountTiers(): array
    {
        $tiers = is_array($this->discount_tiers) ? $this->discount_tiers : [];

        usort($tiers, fn ($a, $b) => ($a['min_quantity'] ?? 0) <=> ($b['min_quantity'] ?? 0));

        return $tiers;
    }

    public function chestPrizes()
    {
        return $this->hasMany(ChestPrize::class);
    }

    public function actionTickets()
    {
        return $this->hasMany(ActionTicket::class);
    }

    public function userKeys()
    {
        return $this->hasMany(UserKey::class);
    }

    public function chestOpenings()
    {
        return $this->hasMany(ChestOpening::class);
    }

    public function winner()
    {
        return $this->belongsTo(User::class, 'winner_user_id');
    }

    public function winnerUser()
    {
        return $this->belongsTo(User::class, 'winner_user_id');
    }

    public function winnerActionTicket()
    {
        return $this->belongsTo(ActionTicket::class, 'winner_action_ticket_id');
    }
}
