<?php

namespace App\Models;

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

class NotificationTargetingRule extends Model
{
    use HasFactory;

    protected $fillable = [
        'notification_id',
        'target_type',
        'target_value',
        'operator',
        'deep_link_url'
    ];

    protected $casts = [
        'target_value' => 'array',
    ];

    /**
     * Get the notification that owns the targeting rule.
     */
    public function notification(): BelongsTo
    {
        return $this->belongsTo(Notification::class);
    }

    /**
     * Check if a user matches this targeting rule.
     */
    public function matchesUser(User $user): bool
    {
        switch ($this->target_type) {
            case 'user_id':
                return $this->checkUserId($user);
            case 'plan_type':
                return $this->checkPlanType($user);
            case 'location':
                return $this->checkLocation($user);
            case 'category':
                return $this->checkCategory($user);
            case 'behavior':
                return $this->checkBehavior($user);
            default:
                return false;
        }
    }

    /**
     * Check if user ID matches.
     */
    protected function checkUserId(User $user): bool
    {
        $userIds = $this->target_value['user_ids'] ?? [];
        return in_array($user->id, $userIds);
    }

    /**
     * Check if user plan type matches.
     */
    protected function checkPlanType(User $user): bool
    {
        $planTypes = $this->target_value['plan_types'] ?? [];
        
        // Get user's current subscription
        $subscription = $user->subscriptions()->where('status', 'active')->first();
        
        if (!$subscription) {
            // User has no active subscription, check if they want to target standard users
            return in_array('standard', $planTypes);
        }

        return in_array($subscription->plan_type, $planTypes);
    }

    /**
     * Check if user location matches.
     */
    protected function checkLocation(User $user): bool
    {
        $locations = $this->target_value['locations'] ?? [];
        $userLocation = $user->city . ', ' . $user->state;
        
        return in_array($userLocation, $locations) || in_array($user->city, $locations) || in_array($user->state, $locations);
    }

    /**
     * Check if user category preferences match.
     */
    protected function checkCategory(User $user): bool
    {
        $categories = $this->target_value['categories'] ?? [];
        
        // This would need to be implemented based on how you track user category preferences
        // For now, we'll return true if categories are specified (can be enhanced later)
        return !empty($categories);
    }

    /**
     * Check if user behavior matches.
     */
    protected function checkBehavior(User $user): bool
    {
        $behaviors = $this->target_value['behaviors'] ?? [];
        
        // This would check user behavior patterns
        // For now, we'll return true if behaviors are specified (can be enhanced later)
        return !empty($behaviors);
    }

    /**
     * Get the targeting rule type label.
     */
    public function getTargetTypeLabelAttribute(): string
    {
        return match($this->target_type) {
            'user_id' => 'User ID',
            'plan_type' => 'Plan Type',
            'location' => 'Location',
            'category' => 'Category',
            'behavior' => 'Behavior',
            'custom' => 'Custom',
            default => 'Unknown'
        };
    }

    /**
     * Get the operator label.
     */
    public function getOperatorLabelAttribute(): string
    {
        return match($this->operator) {
            'equals' => 'Equals',
            'in' => 'In',
            'not_in' => 'Not In',
            'contains' => 'Contains',
            'greater_than' => 'Greater Than',
            'less_than' => 'Less Than',
            'between' => 'Between',
            default => 'Unknown'
        };
    }
}
