<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'firstName',
        'lastName',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    /**
     * Get all invitations sent by this user
     */
    public function sentInvitations()
    {
        return $this->hasMany(Invitation::class, 'inviter_user_id');
    }

    /**
     * Get all friendships for this user
     */
    public function friendships()
    {
        return $this->hasMany(Friendship::class);
    }

    /**
     * Get all friends of this user
     */
    public function friends()
    {
        return $this->belongsToMany(User::class, 'friendships', 'user_id', 'friend_id')
                    ->where('friendships.status', 'active')
                    ->withTimestamps();
    }

    /**
     * Check if this user is friends with another user
     */
    public function isFriendWith(int $userId): bool
    {
        return $this->friendships()
                    ->where('friend_id', $userId)
                    ->where('status', 'active')
                    ->exists();
    }

    /**
     * Add a friend to this user
     */
    public function addFriend(int $userId): void
    {
        if (!$this->isFriendWith($userId) && $this->id !== $userId) {
            Friendship::createFriendship($this->id, $userId);
        }
    }

    /**
     * Remove a friend from this user
     */
    public function removeFriend(int $userId): void
    {
        Friendship::removeFriendship($this->id, $userId);
    }

    /**
     * Get friends count
     */
    public function getFriendsCountAttribute(): int
    {
        return $this->friends()->count();
    }

    /**
     * Get pending invitations count
     */
    public function getPendingInvitationsCountAttribute(): int
    {
        return $this->sentInvitations()->pending()->count();
    }
}
