<?php

namespace App\Domain\Facility\Models;

use App\Domain\Facility\Enums\LayoutType;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class SpaceLayout extends Model
{
    use BelongsToAcademy, HasUuid;

    protected $fillable = [
        'academy_id',
        'facility_id',
        'name',
        'name_ar',
        'layout_type',
        'layout_config',
        'is_recurring',
        'effective_day_of_week',
        'effective_date',
        'start_time',
        'end_time',
        'is_active',
        'sort_order',
        'metadata',
        'created_by',
    ];

    protected function casts(): array
    {
        return [
            'layout_type' => LayoutType::class,
            'layout_config' => 'array',
            'is_recurring' => 'boolean',
            'effective_day_of_week' => 'integer',
            'effective_date' => 'date',
            'is_active' => 'boolean',
            'sort_order' => 'integer',
            'metadata' => 'array',
        ];
    }

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

    public function segments(): HasMany
    {
        return $this->hasMany(SpaceSegment::class)->orderBy('sort_order');
    }

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

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

    public function scopeForDay($query, int $dayOfWeek)
    {
        return $query->where(function ($q) use ($dayOfWeek) {
            $q->where('is_recurring', true)
              ->where('effective_day_of_week', $dayOfWeek);
        });
    }

    public function scopeForDate($query, string $date)
    {
        return $query->where('is_recurring', false)
                     ->where('effective_date', $date);
    }
}
