<?php

namespace App\Models\Catalog;

use App\Models\Branch;
use App\Models\Concerns\Auditable;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Concerns\HasStoredImage;
use App\Models\Concerns\NullableBranchScoped;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class ProductBundle extends Model
{
    use Auditable, BelongsToTenant, HasStoredImage, NullableBranchScoped, SoftDeletes;

    protected $fillable = [
        'uuid', 'name', 'sku', 'description', 'sale_price', 'image_url',
        'branch_id', 'is_active', 'starts_at', 'ends_at',
        'created_by', 'updated_by', 'deleted_by',
    ];

    protected function casts(): array
    {
        return [
            'sale_price' => 'decimal:2',
            'is_active' => 'boolean',
            'starts_at' => 'date',
            'ends_at' => 'date',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (self $bundle): void {
            if (! $bundle->uuid) {
                $bundle->uuid = (string) Str::ulid();
            }
        });
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }

    public function items(): HasMany
    {
        return $this->hasMany(BundleItem::class, 'bundle_id');
    }

    /** Available at the given branch: either branch-specific or global (NULL). */
    public function scopeAvailableAtBranch(Builder $query, ?int $branchId): void
    {
        $query->where(function ($q) use ($branchId) {
            $q->whereNull('branch_id')->when($branchId, fn ($qq) => $qq->orWhere('branch_id', $branchId));
        });
    }

    public function isCurrentlyActive(): bool
    {
        if (! $this->is_active) {
            return false;
        }
        $today = now()->toDateString();
        if ($this->starts_at && $today < $this->starts_at->toDateString()) {
            return false;
        }

        return ! ($this->ends_at && $today > $this->ends_at->toDateString());
    }
}
