<?php

namespace App\Models;

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

class SocialPost extends Model
{
    use HasFactory;
    
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'social_account_id',
        'campaign_id',
        'provider_post_id',
        'title',
        'caption',
        'content',
        'media',
        'permalink',
        'published_at',
        'metrics',
        'raw_json',
        'last_checked_at',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'media' => 'array',
        'metrics' => 'array',
        'raw_json' => 'array',
        'published_at' => 'datetime',
        'last_checked_at' => 'datetime',
    ];

    /**
     * Get the social account that owns the post.
     */
    public function socialAccount()
    {
        return $this->belongsTo(SocialAccount::class);
    }
    
    /**
     * Get the campaign that owns the post.
     */
    public function campaign()
    {
        return $this->belongsTo(Campaign::class);
    }
    
    /**
     * Get the user that owns the post through the social account.
     */
    public function user()
    {
        return $this->hasOneThrough(User::class, SocialAccount::class, 'id', 'id', 'social_account_id', 'user_id');
    }

    /**
     * Get the views count from metrics.
     *
     * @return int
     */
    public function getViewsCount()
    {
        return $this->metrics['views'] ?? 0;
    }

    /**
     * Get the likes count from metrics.
     *
     * @return int
     */
    public function getLikesCount()
    {
        return $this->metrics['likes'] ?? 0;
    }

    /**
     * Get the comments count from metrics.
     *
     * @return int
     */
    public function getCommentsCount()
    {
        return $this->metrics['comments'] ?? 0;
    }

    /**
     * Get the shares count from metrics.
     *
     * @return int
     */
    public function getSharesCount()
    {
        return $this->metrics['shares'] ?? 0;
    }
    
    /**
     * Get the saves count from metrics.
     *
     * @return int
     */
    public function getSavesCount()
    {
        return $this->metrics['saves'] ?? 0;
    }

    /**
     * Get the engagement rate.
     *
     * @return float
     */
    public function getEngagementRate()
    {
        $views = $this->getViewsCount();
        if ($views <= 0) {
            return 0;
        }

        $engagements = $this->getLikesCount() + $this->getCommentsCount() + $this->getSharesCount() + $this->getSavesCount();
        return round(($engagements / $views) * 100, 2);
    }
}
