<?php

namespace App\Models;

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 HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    // Relationships
    public function sentFriendRequests()
    {
        return $this->hasMany(FriendRequest::class, 'sender_id');
    }

    public function receivedFriendRequests()
    {
        return $this->hasMany(FriendRequest::class, 'receiver_id');
    }

    public function friends()
    {
        $acceptedAsSender = $this->hasMany(FriendRequest::class, 'sender_id')
            ->where('status', 'accepted')
            ->join('users', 'friend_requests.receiver_id', '=', 'users.id')
            ->select('users.id', 'users.name', 'users.email', 'users.created_at');

        $acceptedAsReceiver = $this->hasMany(FriendRequest::class, 'receiver_id')
            ->where('status', 'accepted')
            ->join('users', 'friend_requests.sender_id', '=', 'users.id')
            ->select('users.id', 'users.name', 'users.email', 'users.created_at');

        return $acceptedAsSender->union($acceptedAsReceiver);
    }

    // Helper methods
    public function isFriendWith($userId)
    {
        return $this->friends()->where('users.id', $userId)->exists();
    }

    public function hasPendingRequestTo($userId)
    {
        return $this->sentFriendRequests()
            ->where('receiver_id', $userId)
            ->where('status', 'pending')
            ->exists();
    }

    public function hasPendingRequestFrom($userId)
    {
        return $this->receivedFriendRequests()
            ->where('sender_id', $userId)
            ->where('status', 'pending')
            ->exists();
    }
}