<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Friendship extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'friend_id',
        'status'
    ];

    /**
     * Get the user who owns the friendship
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the friend user
     */
    public function friend()
    {
        return $this->belongsTo(User::class, 'friend_id');
    }

    /**
     * Create a bidirectional friendship between two users
     */
    public static function createFriendship(int $userId, int $friendId): void
    {
        // Prevent duplicate friendships
        if (static::friendshipExists($userId, $friendId)) {
            return;
        }

        // Create bidirectional friendship
        static::create([
            'user_id' => $userId,
            'friend_id' => $friendId,
            'status' => 'active'
        ]);

        static::create([
            'user_id' => $friendId,
            'friend_id' => $userId,
            'status' => 'active'
        ]);
    }

    /**
     * Remove bidirectional friendship between two users
     */
    public static function removeFriendship(int $userId, int $friendId): void
    {
        // Remove bidirectional friendship
        static::where([
            ['user_id', $userId],
            ['friend_id', $friendId]
        ])->delete();

        static::where([
            ['user_id', $friendId],
            ['friend_id', $userId]
        ])->delete();
    }

    /**
     * Check if friendship exists between two users
     */
    public static function friendshipExists(int $userId, int $friendId): bool
    {
        return static::where([
            ['user_id', $userId],
            ['friend_id', $friendId],
            ['status', 'active']
        ])->exists();
    }

    /**
     * Scope for active friendships
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }
}
