<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class Group extends Model
{
    protected $fillable = ['name', 'slug', 'status', 'notes'];

    protected static function booted()
    {
        static::creating(function ($group) {
            if (empty($group->slug)) {
                $group->slug = Str::slug($group->name) . '-' . Str::random(4);
            }
        });
    }

    // members
    public function members(): HasMany
    {
        return $this->hasMany(GroupMember::class);
    }

    // active members relation convenience
    public function activeMembers()
    {
        return $this->members()->where('status', 'active')->with('user');
    }

    // count active members
    public function activeMembersCount(): int
    {
        return $this->members()->where('status', 'active')->count();
    }

    // helper to check if group meets the minimum requirement
    public function meetsMinimumMembers(int $min = 5): bool
    {
        return $this->activeMembersCount() >= $min;
    }

     public function users()
    {
        return $this->belongsToMany(
            User::class,
            'group_members',
            'group_id',
            'user_id'
        );
    }

}
