<?php

namespace App\Models\Mall;

use App\Models\Account;
use App\Models\Game\Player\ItemProto;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;

class MallHistory extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * The connection name for the model.
     *
     * @var string|null
     */
    protected $connection = 'website';

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'mall_history';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'account_id',
        'transaction_type',
        'item_vnum',
        'item_count',
        'currency_type',
        'amount_spent',
        'description',
        'created_at',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'created_at' => 'datetime',
    ];

    /**
     * Get the account that owns this history record
     *
     * @return BelongsTo
     */
    public function account(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'account_id', 'id');
    }

    /**
     * Get the associated item_proto entry
     *
     * @return HasOne
     */
    public function proto(): HasOne
    {
        return $this->hasOne(ItemProto::class, 'vnum', 'item_vnum');
    }

    /**
     * Record a purchase in history
     *
     * @param int $accountId
     * @param int $vnum
     * @param int $count
     * @param string $currencyType ('cash' or 'mileage')
     * @param int $amount
     * @param string|null $description
     * @return self
     */
    public static function recordPurchase(
        int $accountId,
        int $vnum,
        int $count,
        string $currencyType,
        int $amount,
        ?string $description = null
    ): self {
        return self::create([
            'account_id' => $accountId,
            'transaction_type' => 'purchase',
            'item_vnum' => $vnum,
            'item_count' => $count,
            'currency_type' => $currencyType,
            'amount_spent' => $amount,
            'description' => $description,
        ]);
    }

    /**
     * Record a wheel spin in history
     *
     * @param int $accountId
     * @param string $wheelType ('wheel_spin' or 'small_wheel_spin')
     * @param int $vnum
     * @param int $count
     * @param int $amount
     * @return self
     */
    public static function recordWheelSpin(
        int $accountId,
        string $wheelType,
        int $vnum,
        int $count,
        int $amount
    ): self {
        return self::create([
            'account_id' => $accountId,
            'transaction_type' => $wheelType,
            'item_vnum' => $vnum,
            'item_count' => $count,
            'currency_type' => 'cash',
            'amount_spent' => $amount,
            'description' => ucfirst(str_replace('_', ' ', $wheelType)),
        ]);
    }

    /**
     * Get purchase history for an account within a time period
     *
     * @param int $accountId
     * @param int $days
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function getRecentHistory(int $accountId, int $days = 30)
    {
        return self::where('account_id', $accountId)
            ->where('created_at', '>=', now()->subDays($days))
            ->orderBy('created_at', 'desc')
            ->get();
    }

    /**
     * Get spending summary for an account
     *
     * @param int $accountId
     * @param int $days
     * @return array
     */
    public static function getSpendingSummary(int $accountId, int $days = 30): array
    {
        $summary = self::where('account_id', $accountId)
            ->where('created_at', '>=', now()->subDays($days))
            ->selectRaw('
                currency_type,
                SUM(amount_spent) as total_spent,
                COUNT(*) as transaction_count
            ')
            ->groupBy('currency_type')
            ->get();

        return [
            'cash_spent' => $summary->where('currency_type', 'cash')->first()->total_spent ?? 0,
            'mileage_spent' => $summary->where('currency_type', 'mileage')->first()->total_spent ?? 0,
            'total_transactions' => $summary->sum('transaction_count'),
        ];
    }
}
