<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class Lot extends Model implements HasMedia
{
    use HasFactory, SoftDeletes, InteractsWithMedia;

    protected $fillable = [
        'auction_id',
        'title',
        'slug',
        'description',
        'starting_bid',
        'current_bid',
        'buy_now_price',
        'reserve_price',
        'bid_increment',
        'starts_at',
        'ends_at',
        'status', // draft, scheduled, live, ended, cancelled
        'ai_analysis', // JSON: identification, comps, suggested_starting_bids, confidence
        'category_id',
        'condition',
        'serial_number',
        'is_featured',
        'view_count',
        'watch_count',
    ];

    protected $casts = [
        'ai_analysis' => 'array',
        'starts_at' => 'datetime',
        'ends_at' => 'datetime',
        'starting_bid' => 'decimal:2',
        'current_bid' => 'decimal:2',
        'buy_now_price' => 'decimal:2',
        'reserve_price' => 'decimal:2',
        'bid_increment' => 'decimal:2',
        'is_featured' => 'boolean',
    ];

    public function auction()
    {
        return $this->belongsTo(Auction::class);
    }

    public function bids()
    {
        return $this->hasMany(Bid::class)->latest();
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function highestBid()
    {
        return $this->bids()->orderByDesc('amount')->first();
    }

    public function isLive(): bool
    {
        return $this->status === 'live'
            && now()->between($this->starts_at, $this->ends_at);
    }

    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('images')
            ->useDisk('public');
        $this->addMediaCollection('primary')
            ->singleFile()
            ->useDisk('public');
    }
}
