<?php

namespace App\Models;

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

class UserPreference extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'preferred_categories',
        'preferred_price_ranges',
        'preferred_listing_types',
        'preferred_conditions',
        'preferred_locations',
        'onboarding_completed',
        'ui_mode',
    ];

    protected function casts(): array
    {
        return [
            'preferred_categories' => 'array',
            'preferred_price_ranges' => 'array',
            'preferred_listing_types' => 'array',
            'preferred_conditions' => 'array',
            'preferred_locations' => 'array',
            'onboarding_completed' => 'boolean',
        ];
    }

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

    public static function getDefaultPreferences()
    {
        return [
            'preferred_categories' => [],
            'preferred_price_ranges' => [
                ['min' => 0, 'max' => 500],
                ['min' => 500, 'max' => 1500],
                ['min' => 1500, 'max' => null]
            ],
            'preferred_listing_types' => ['sale', 'trade'],
            'preferred_conditions' => ['excellent', 'good', 'fair'],
            'preferred_locations' => [],
        ];
    }

    public function hasPreferredCategory($categoryId)
    {
        return in_array($categoryId, $this->preferred_categories ?? []);
    }

    public function hasPreferredPriceRange($price)
    {
        if (!$this->preferred_price_ranges) {
            return true;
        }

        foreach ($this->preferred_price_ranges as $range) {
            $min = $range['min'] ?? 0;
            $max = $range['max'] ?? null;
            
            if ($max === null) {
                return $price >= $min;
            }
            
            if ($price >= $min && $price <= $max) {
                return true;
            }
        }
        
        return false;
    }
}