<?php

declare(strict_types=1);

namespace App\Models;

use App\Enums\GroupType;
use App\Services\BranchAccessService;
use Database\Factories\GroupFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Group extends Model
{
    /** @use HasFactory<GroupFactory> */
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'branch_id',
        'leader_member_id',
        'name',
        'type',
        'description',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'type' => GroupType::class,
            'is_active' => 'boolean',
        ];
    }

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

    public function leaderMember(): BelongsTo
    {
        return $this->belongsTo(Member::class, 'leader_member_id');
    }

    public function members(): BelongsToMany
    {
        return $this->belongsToMany(Member::class, 'group_member')
            ->using(GroupMember::class)
            ->withPivot(['role_in_group', 'joined_at'])
            ->withTimestamps();
    }

    /**
     * Org-wide groups (branch_id null) are visible to everyone; branch groups
     * follow the normal scoping. GroupPolicy governs who may *manage* them.
     */
    public function scopeVisibleTo(Builder $query, User $user): Builder
    {
        $branchIds = app(BranchAccessService::class)->accessibleBranchIds($user);

        if ($branchIds === null) {
            return $query;
        }

        return $query->where(
            fn (Builder $q) => $q->whereIn('branch_id', $branchIds)->orWhereNull('branch_id'),
        );
    }

    /**
     * Cross-branch reads must 404, not 403 — see Member::resolveRouteBinding.
     */
    public function resolveRouteBinding($value, $field = null)
    {
        $query = static::query();
        $user = auth()->user();

        if ($user) {
            $query->visibleTo($user);
        }

        return $query->where($field ?? $this->getRouteKeyName(), $value)->first();
    }
}
