<?php

namespace App\Models\CMS\Marketing;

use App\Models\Ecommerce\Product\Product\Product;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Spatie\Translatable\HasTranslations;

class FlashSale extends Model
{
    use HasFactory;
    use HasTranslations;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'id',
        'title',
        'starts_at',
        'ends_at',
        'is_visible',
    ];

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

    /**
     * Translatable attributes.
     *
     * @var array<string>
     */
    public $translatable = ['title'];

    /**
     * Related products.
     */
    public function products(): BelongsToMany
    {
        return $this->belongsToMany(Product::class)
            ->withTimestamps();
    }

    /**
     * Active flash sales are visible and inside their timer window.
     */
    public function scopeActive(Builder $query): Builder
    {
        return $query
            ->where('is_visible', true)
            ->where('starts_at', '<=', now())
            ->where('ends_at', '>', now());
    }
}
