<?php

namespace App\Models;

use App\Campaigns\Manager\Canonical;
use Database\Factories\CampaignPlatformEntityFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * The last confirmed platform state of one object inside a campaign.
 *
 * One row per campaign, ad set, ad group, asset group, campaign group, ad or
 * sponsored creative, in the platform's own vocabulary. It is a record of what
 * the platform said on the last successful read, not a draft and not something
 * to send back: the settings are a normalized projection, and writing them to
 * a platform would erase whatever the projection leaves out.
 */
#[Fillable([
    'campaign_id', 'platform', 'entity_type', 'external_id', 'parent_type', 'parent_external_id',
    'name', 'status', 'effective_status', 'settings', 'fingerprint',
    'first_seen_at', 'last_seen_at', 'last_changed_at', 'removed_at',
])]
class CampaignPlatformEntity extends Model
{
    /** @use HasFactory<CampaignPlatformEntityFactory> */
    use HasFactory;

    protected function casts(): array
    {
        return [
            'settings' => 'array',
            'first_seen_at' => 'datetime',
            'last_seen_at' => 'datetime',
            'last_changed_at' => 'datetime',
            'removed_at' => 'datetime',
        ];
    }

    public function campaign(): BelongsTo
    {
        return $this->belongsTo(Campaign::class);
    }

    public function drifts(): HasMany
    {
        return $this->hasMany(CampaignPlatformDrift::class);
    }

    /** @param  Builder<self>  $query */
    public function edits(): HasMany
    {
        return $this->hasMany(CampaignEntityEdit::class);
    }

    public function scopePresent(Builder $query): void
    {
        $query->whereNull('removed_at');
    }

    /**
     * What a person can have changed on this object: everything the read
     * holds except effective_status, which the platform derives on its own
     * (ad review, a parent pausing) and nobody sets. An edit proposed against
     * this goes stale only when one of these moves.
     */
    public function editBaseline(): string
    {
        return hash('sha256', json_encode([
            'name' => $this->name,
            'status' => $this->status,
            'parent' => $this->parent_external_id,
            'settings' => Canonical::sort((array) $this->settings),
        ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION));
    }
}
