<?php

namespace App\Models;

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

class NotificationTarget extends Model
{
    use HasFactory;

    protected $fillable = [
        'notification_id',
        'target_type',
        'target_id',
    ];

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

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

    public function scopeByTarget($query, $type, $id = null)
    {
        $query->where('target_type', $type);
        if ($id) {
            $query->where('target_id', $id);
        }
        return $query;
    }

    // Helper Methods
    public function getTargetUsers()
    {
        switch ($this->target_type) {
            case 'all':
                return \App\Models\User::where('is_guest', false)->get();

            case 'country':
                return \App\Models\User::where('current_country_id', $this->target_id)
                    ->orWhere('country_id', $this->target_id)
                    ->get();

            case 'language':
                return \App\Models\User::where('language_id', $this->target_id)->get();

            case 'role':
                return \App\Models\User::where('role', $this->target_id)->get();

            case 'user':
                return \App\Models\User::where('id', $this->target_id)->get();

            case 'store_followers':
                return \App\Models\User::whereHas('subscriptions', function ($q) {
                    $q->where('subscribable_type', \App\Models\CountryStore::class)
                        ->where('subscribable_id', $this->target_id)
                        ->where('type', 'follow');
                })->get();

            case 'brand_followers':
                return \App\Models\User::whereHas('subscriptions', function ($q) {
                    $q->where('subscribable_type', \App\Models\Brand::class)
                        ->where('subscribable_id', $this->target_id)
                        ->where('type', 'follow');
                })->get();

            default:
                return collect();
        }
    }
}
