<?php

namespace App\Models;

use Database\Factories\CampaignEntityEditFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * One change to one platform object, asked for in the campaign manager.
 *
 * The changes are fixed when proposed and never edited afterwards, and the
 * fingerprint of the object as it was read at that moment travels with them.
 * Approving therefore approves exactly this patch against exactly that state:
 * if the platform has moved on by the time it is applied, it is not applied.
 *
 * Most rows change fields on the object. A delete or a duplicate changes no
 * field: its changes are empty, and what was read for it (lifetime delivery
 * before a delete, the copy after a duplicate) is kept in details.
 *
 * @property array<string, array{before: mixed, after: mixed}> $changes
 * @property array{spend?: float, impressions?: int, currency?: string, copy_id?: string, copy_entity_id?: int|null, copy_name?: string|null, pending?: bool}|null $details
 */
#[Fillable([
    'campaign_id', 'campaign_platform_entity_id', 'user_id', 'campaign_change_id',
    'platform', 'entity_type', 'external_id', 'action', 'changes', 'details', 'base_fingerprint', 'state',
    'readback', 'error', 'approved_at', 'applied_at', 'verified_at',
])]
class CampaignEntityEdit extends Model
{
    /** @use HasFactory<CampaignEntityEditFactory> */
    use HasFactory;

    /** Written down and waiting for the user to confirm it. */
    public const string Proposed = 'proposed';

    /** Sent, and the platform read back with exactly the new values. */
    public const string Applied = 'applied';

    /** Sent and accepted, but the platform read back something else. */
    public const string Unconfirmed = 'unconfirmed';

    /** Not sent: the object changed on the platform after it was proposed. */
    public const string Stale = 'stale';

    /** Not sent, or refused by the platform. */
    public const string Failed = 'failed';

    public const string Cancelled = 'cancelled';

    /** Fields on the object change. */
    public const string Edit = 'edit';

    /** The object is removed from the platform. */
    public const string Delete = 'delete';

    /** A paused copy of the object is made beside it. */
    public const string Duplicate = 'duplicate';

    /** @var array<string, mixed> */
    protected $attributes = ['action' => self::Edit];

    protected function casts(): array
    {
        return [
            'changes' => 'array',
            'details' => 'array',
            'readback' => 'array',
            'approved_at' => 'datetime',
            'applied_at' => 'datetime',
            'verified_at' => 'datetime',
        ];
    }

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

    public function entity(): BelongsTo
    {
        return $this->belongsTo(CampaignPlatformEntity::class, 'campaign_platform_entity_id');
    }

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

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

    /** A delete or a duplicate, rather than new values for fields. */
    public function isStructural(): bool
    {
        return $this->action !== self::Edit;
    }

    /** One line for a delete or a duplicate, as the history shows it. */
    public function summary(): ?string
    {
        return match ($this->action) {
            self::Delete => ($this->details['pending'] ?? false) ? 'Delete (pending on the platform)' : 'Delete',
            self::Duplicate => filled($this->details['copy_id'] ?? null)
                ? sprintf('%s copy %s', $this->platform === 'linkedin' ? 'Draft' : 'Paused', $this->details['copy_name'] ?? $this->details['copy_id'])
                : ($this->platform === 'linkedin' ? 'Draft copy' : 'Paused copy'),
            default => null,
        };
    }

    public function isOpen(): bool
    {
        return $this->state === self::Proposed;
    }

    /**
     * The fields and the values the platform should hold once this is applied.
     *
     * Read through getAttribute(): inside the model, $this->changes is
     * Eloquent's own record of dirty attributes, not this column.
     *
     * @return array<string, mixed>
     */
    public function patch(): array
    {
        return array_map(fn (array $change): mixed => $change['after'] ?? null, (array) $this->getAttribute('changes'));
    }
}
