<?php

namespace App\Models;

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

class Subscription extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'subscribable_type',
        'subscribable_id',
        'type',
    ];

    // Relations
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function subscribable()
    {
        return $this->morphTo();
    }

    // Scopes
    public function scopeByUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    public function scopeByType($query, $type)
    {
        return $query->where('type', $type);
    }

    public function scopeBySubscribable($query, $type, $id = null)
    {
        $query->where('subscribable_type', $type);
        if ($id) {
            $query->where('subscribable_id', $id);
        }
        return $query;
    }

    public function scopeFollowers($query)
    {
        return $query->where('type', 'follow');
    }

    // Helper Methods
    public static function follow($userId, $subscribable)
    {
        return static::firstOrCreate([
            'user_id' => $userId,
            'subscribable_type' => get_class($subscribable),
            'subscribable_id' => $subscribable->id,
            'type' => 'follow',
        ]);
    }

    public static function unfollow($userId, $subscribable)
    {
        return static::where([
            'user_id' => $userId,
            'subscribable_type' => get_class($subscribable),
            'subscribable_id' => $subscribable->id,
            'type' => 'follow',
        ])->delete();
    }

    public static function isFollowing($userId, $subscribable)
    {
        return static::where([
            'user_id' => $userId,
            'subscribable_type' => get_class($subscribable),
            'subscribable_id' => $subscribable->id,
            'type' => 'follow',
        ])->exists();
    }
}