<?php

// app/Models/Stall.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Stall extends Model
{
    use HasFactory;

    protected $fillable = [
        'market_id', 'merchant_id', 'code', 'section', 'size',
        'monthly_fee', 'status', 'occupied_since', 'metadata',
    ];

    protected $casts = [
        'occupied_since' => 'date',
        'metadata' => 'array',
    ];

    const STATUS = [
        'available' => 'Livre',
        'occupied' => 'Ocupado',
        'maintenance' => 'Manutenção',
        'reserved' => 'Reservado',
    ];

    public function market()
    {
        return $this->belongsTo(Market::class);
    }

    public function merchant()
    {
        return $this->belongsTo(Merchant::class);
    }

    public function history()
    {
        return $this->hasMany(StallHistory::class);
    }

    public function scopeAvailable($query)
    {
        return $query->where('status', 'available');
    }

    public function scopeOccupied($query)
    {
        return $query->where('status', 'occupied');
    }

    public function assignTo(Merchant $merchant)
    {
        $this->update([
            'merchant_id' => $merchant->id,
            'status' => 'occupied',
            'occupied_since' => now(),
        ]);

        StallHistory::create([
            'stall_id' => $this->id,
            'merchant_id' => $merchant->id,
            'occupied_from' => now(),
            'monthly_fee' => $this->monthly_fee,
        ]);

        return $this;
    }

    public function release()
    {
        $history = $this->history()->whereNull('occupied_until')->latest()->first();
        if ($history) {
            $history->update(['occupied_until' => now()]);
        }

        $this->update([
            'merchant_id' => null,
            'status' => 'available',
            'occupied_since' => null,
        ]);

        return $this;
    }
}
