<?php

namespace App\Domain\Facility\Models;

use App\Domain\Facility\Enums\FacilityStatus;
use App\Domain\Facility\Enums\FacilityType;
use App\Domain\Identity\Models\Branch;
use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Domain\Shared\Traits\ManglesUniqueOnDelete;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Domain\Shared\Traits\BelongsToBranch;

class Facility extends Model
{
    use BelongsToAcademy, HasUuid, SoftDeletes, Auditable, ManglesUniqueOnDelete, BelongsToBranch;

    protected array $uniqueFieldsToMangle = ['code'];

    protected $fillable = [
        'academy_id',
        'branch_id',
        'name',
        'name_ar',
        'code',
        'type',
        'status',
        'description',
        'description_ar',
        'capacity',
        'surface_type',
        'area_sqm',
        'length_m',
        'width_m',
        'is_indoor',
        'has_lighting',
        'has_ac',
        'operating_start',
        'operating_end',
        'rental_cost_per_hour',
        'monthly_rental_cost',
        'address',
        'latitude',
        'longitude',
        'amenities',
        'metadata',
        'photo_path',
        'sort_order',
        'created_by',
    ];

    protected function casts(): array
    {
        return [
            'type' => FacilityType::class,
            'status' => FacilityStatus::class,
            'capacity' => 'integer',
            'area_sqm' => 'decimal:2',
            'length_m' => 'decimal:2',
            'width_m' => 'decimal:2',
            'is_indoor' => 'boolean',
            'has_lighting' => 'boolean',
            'has_ac' => 'boolean',
            'rental_cost_per_hour' => 'integer',
            'monthly_rental_cost' => 'integer',
            'amenities' => 'array',
            'metadata' => 'array',
            'sort_order' => 'integer',
        ];
    }

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

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

    public function layouts(): HasMany
    {
        return $this->hasMany(SpaceLayout::class);
    }

    public function activeLayout(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne(SpaceLayout::class)->where('is_active', true)->orderBy('sort_order');
    }

    public function reservations(): HasMany
    {
        return $this->hasMany(SpaceReservation::class);
    }

    /**
     * Sports this facility can host. Empty = hosts anything (the default for
     * facilities created before the link existed).
     */
    public function activities(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        // facility_activities.academy_id is NOT NULL and the pivot has no model to
        // stamp it, so a plain sync() threw on every tenant — which is why no
        // facility anywhere has ever had a sport recorded against it, and why the
        // schedule builder still offers swimming groups on a football pitch.
        // withPivotValue both fills it on write and scopes it on read.
        return $this->belongsToMany(
            \App\Domain\Training\Models\Activity::class,
            'facility_activities',
            'facility_id',
            'activity_id'
        )->withPivotValue('academy_id', $this->academy_id)->withTimestamps();
    }

    // No scopeForBranch() here. A method on the class wins over the one the
    // trait provides, so this override used to shadow
    // BelongsToBranch::scopeForBranch() — the documented escape hatch for a
    // deliberate cross-branch read. It only ANDed a branch_id clause onto a
    // query BranchScope had already narrowed, so Facility::forBranch($other)
    // returned nothing at all instead of that branch's facilities. Removing it
    // restores the trait version, which lifts the scope first.

    public function scopeActive($query)
    {
        return $query->where('status', FacilityStatus::Active);
    }
}
