<?php

namespace App\Models;

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

class AdPerformanceMetric extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'ad_variant_id',
        'platform',
        'impressions',
        'clicks',
        'conversions',
        'spend',
        'ctr',
        'conversion_rate',
        'cpc',
        'cpm',
        'roas',
        'last_synced_at',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'impressions' => 'integer',
        'clicks' => 'integer',
        'conversions' => 'integer',
        'spend' => 'decimal:2',
        'ctr' => 'decimal:4',
        'conversion_rate' => 'decimal:4',
        'cpc' => 'decimal:4',
        'cpm' => 'decimal:4',
        'roas' => 'decimal:4',
        'last_synced_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * Get the ad variant that owns the performance metrics.
     */
    public function adVariant()
    {
        return $this->belongsTo(AdVariant::class);
    }

    /**
     * Scope a query to only include metrics for a specific platform.
     */
    public function scopeForPlatform($query, $platform)
    {
        return $query->where('platform', $platform);
    }

    /**
     * Calculate the cost per click (CPC).
     */
    public function calculateCPC()
    {
        if ($this->clicks == 0) {
            return 0;
        }
        return $this->spend / $this->clicks;
    }

    /**
     * Calculate the cost per thousand impressions (CPM).
     */
    public function calculateCPM()
    {
        if ($this->impressions == 0) {
            return 0;
        }
        return ($this->spend / $this->impressions) * 1000;
    }

    /**
     * Calculate the return on ad spend (ROAS).
     */
    public function calculateROAS()
    {
        if ($this->spend == 0) {
            return 0;
        }
        // Assuming each conversion is worth $10 in revenue for this example
        // In a real implementation, this would be based on actual product values
        $revenue = $this->conversions * 10;
        return $revenue / $this->spend;
    }
}