<?php

namespace App\Models;

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

class SocialAggregate extends Model
{
    use HasFactory;
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'user_id',
        'brand_id',
        'tenant_id',
        'provider',
        'key',
        'value',
        'computed_at',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'value' => 'array',
        'computed_at' => 'datetime',
    ];

    /**
     * Get the user that owns the aggregate.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    
    /**
     * Get the brand that owns the aggregate.
     */
    public function brand()
    {
        return $this->belongsTo(Brand::class);
    }
    
    /**
     * Get the tenant that owns the aggregate.
     */
    public function tenant()
    {
        return $this->belongsTo(Tenant::class);
    }

    /**
     * Get the numeric value.
     *
     * @return float|int|null
     */
    public function getNumericValue()
    {
        if (is_numeric($this->value)) {
            return $this->value;
        }

        if (is_array($this->value) && isset($this->value['value'])) {
            return $this->value['value'];
        }

        return null;
    }

    /**
     * Get the previous value for comparison.
     *
     * @return float|int|null
     */
    public function getPreviousValue()
    {
        if (is_array($this->value) && isset($this->value['previous'])) {
            return $this->value['previous'];
        }

        return null;
    }

    /**
     * Get the change percentage.
     *
     * @return float|null
     */
    public function getChangePercentage()
    {
        $current = $this->getNumericValue();
        $previous = $this->getPreviousValue();

        if ($previous === null || $previous <= 0) {
            return null;
        }

        return round((($current - $previous) / $previous) * 100, 2);
    }

    /**
     * Check if the change is positive.
     *
     * @return bool|null
     */
    public function isChangePositive()
    {
        $percentage = $this->getChangePercentage();
        if ($percentage === null) {
            return null;
        }

        return $percentage >= 0;
    }
}
