<?php

namespace App\Domain\Pricing\Models;

use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class BasePrice extends Model
{
    use BelongsToAcademy, HasUuid, SoftDeletes;

    protected $fillable = [
        'academy_id',
        'priceable_type',
        'priceable_id',
        'branch_id',
        'name_ar',
        'name',
        'amount',
        'currency',
        'effective_from',
        'effective_to',
        'is_active',
        'priority',
        'notes',
        'created_by',
        'metadata',
    ];

    protected $casts = [
        'amount' => 'integer',
        'is_active' => 'boolean',
        'effective_from' => 'date',
        'effective_to' => 'date',
        'priority' => 'integer',
        'metadata' => 'array',
    ];

    // ─── Relationships ────────────────────────────────────────────────

    public function priceable(): MorphTo
    {
        return $this->morphTo();
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(\App\Domain\Shared\Models\Branch::class);
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class, 'created_by');
    }

    // ─── Scopes ───────────────────────────────────────────────────────

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    public function scopeEffectiveOn(Builder $query, $date): Builder
    {
        return $query->where('effective_from', '<=', $date)
            ->where(function (Builder $q) use ($date) {
                $q->whereNull('effective_to')
                    ->orWhere('effective_to', '>=', $date);
            });
    }

    public function scopeForBranch(Builder $query, ?int $branchId): Builder
    {
        return $query->where(function (Builder $q) use ($branchId) {
            $q->whereNull('branch_id')
                ->orWhere('branch_id', $branchId);
        });
    }
}
