<?php

namespace App\Models\Mall;

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

class MallStorage 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_storage';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'owner_id',
        'count',
        'vnum',
        'socket0',
        'socket1',
        'socket2',
        'socket3',
        'socket4',
        'socket5',
        'attrtype0',
        'attrvalue0',
        'attrtype1',
        'attrvalue1',
        'attrtype2',
        'attrvalue2',
        'attrtype3',
        'attrvalue3',
        'attrtype4',
        'attrvalue4',
        'attrtype5',
        'attrvalue5',
        'attrtype6',
        'attrvalue6',
    ];

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

    /**
     * Get grouped storage items for a user
     * Groups by vnum and sockets to show consolidated counts
     *
     * @param int $ownerId
     * @return \Illuminate\Support\Collection
     */
    public static function getGroupedItems(int $ownerId)
    {
        return self::where('owner_id', $ownerId)
            ->selectRaw('
                vnum,
                SUM(count) as total_count,
                COUNT(*) as stack_count,
                MAX(id) as sample_id,
                socket0, socket1, socket2, socket3, socket4, socket5,
                attrtype0, attrvalue0, attrtype1, attrvalue1, attrtype2, attrvalue2,
                attrtype3, attrvalue3, attrtype4, attrvalue4, attrtype5, attrvalue5,
                attrtype6, attrvalue6
            ')
            ->groupBy([
                'vnum', 'socket0', 'socket1', 'socket2', 'socket3', 'socket4', 'socket5',
                'attrtype0', 'attrvalue0', 'attrtype1', 'attrvalue1', 'attrtype2', 'attrvalue2',
                'attrtype3', 'attrvalue3', 'attrtype4', 'attrvalue4', 'attrtype5', 'attrvalue5',
                'attrtype6', 'attrvalue6'
            ])
            ->get();
    }

    /**
     * Get total unique item count for a user
     * Counts unique vnums (not individual stacks)
     *
     * @param int $ownerId
     * @return int
     */
    public static function getUniqueItemCount(int $ownerId): int
    {
        return (int) self::where('owner_id', $ownerId)
            ->selectRaw('COUNT(DISTINCT vnum) as unique_count')
            ->value('unique_count');
    }
}
