<?php

namespace App\Models\Messenger;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Builder;

class Block extends Model
{
    protected $table = 'blocked_users';
    
    protected $fillable = [
        'user_id',
        'blocked_user_id',
    ];

    public function blocker(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function blocked(): BelongsTo
    {
        return $this->belongsTo(User::class, 'blocked_user_id');
    }

    public function scopeForBlocker(Builder $query, int $blockerId): Builder
    {
        return $query->where('user_id', $blockerId);
    }

    public function scopeForBlocked(Builder $query, int $blockedId): Builder
    {
        return $query->where('blocked_user_id', $blockedId);
    }

    public static function isBlocked(int $userId1, int $userId2): bool
    {
        return self::where(function ($query) use ($userId1, $userId2) {
            $query->where('user_id', $userId1)->where('blocked_user_id', $userId2);
        })->orWhere(function ($query) use ($userId1, $userId2) {
            $query->where('user_id', $userId2)->where('blocked_user_id', $userId1);
        })->exists();
    }

    public static function blockUser(int $blockerId, int $blockedId): bool
    {
        if ($blockerId === $blockedId) {
            return false;
        }

        return self::updateOrCreate([
            'user_id' => $blockerId, 
            'blocked_user_id' => $blockedId
        ]);
    }

    public static function unblockUser(int $blockerId, int $blockedId): bool
    {
        return self::where('user_id', $blockerId)
            ->where('blocked_user_id', $blockedId)
            ->delete();
    }
}
