<?php

namespace App\Models\Concerns;

use App\Models\CampaignAdSet;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

/**
 * A campaign's ad sets, and the campaign's own view of the first one.
 *
 * Targeting, schedule, optimisation and the bid used to be columns on
 * campaigns, which worked only because there was always exactly one ad set.
 * They are rows now, so a second ad set has somewhere to put its own answers.
 *
 * The rest of the app still says $campaign->locations, and that is deliberate:
 * nearly eight hundred call sites ask a campaign for its targeting, its dates
 * and its budget, and rewriting all of them to reach through a relation would
 * be a very large change for no gain in meaning. So those reads and writes are
 * forwarded to the first ad set. There is still exactly one home for each
 * value - the ad set row - and this is the campaign addressing it, not a second
 * copy of it.
 *
 * Writes follow Eloquent's own timing rather than landing immediately: setting
 * an attribute marks the ad set dirty and saving the campaign saves it too, so
 * $campaign->update(['budget' => 20]) persists and $campaign->budget = 20 on
 * its own does not, which is what the same two lines do for a campaign's own
 * columns.
 */
trait HasAdSets
{
    /**
     * The fields an ad set answers for its campaign.
     *
     * Who to show the ads to, when to show them, and what to optimise for.
     * Nothing conditional: a field's home may not depend on another field's
     * value.
     *
     * The money is not here, and that is the one decision in this file worth
     * explaining. budget, budget_mode, budget_level, bid_strategy and
     * bid_amount stay on the campaign, because what the buyer states is a
     * campaign-level arrangement - under Advantage campaign budget that is
     * literally what Meta holds - and MetaPublisher::byEntity() already routes
     * it to the campaign or the ad set on the way out. An ad set that wants its
     * own amount overrides it on its own row; ad set 1 normally does not.
     *
     * Routing the money by budget_level instead was tried and is wrong. The
     * home would depend on a mutable sibling attribute, so the order of a
     * single update() decided where the value landed: ['budget_mode' =>
     * 'lifetime', 'budget_level' => 'campaign'] wrote the mode to the ad set
     * and then read it back from the campaign, as null. Moving the money
     * between levels afterwards would have orphaned it the same way.
     *
     * @var list<string>
     */
    public const OWNED_BY_AD_SET = [
        'locations', 'audience', 'placements',
        'optimization_goal', 'conversion_event',
        'starts_at', 'ends_at',
    ];

    /**
     * The first ad set, before this campaign has been saved and has one.
     *
     * A campaign created with targeting in the same breath - which every
     * importer and half the tests do - sets those attributes before there is a
     * row to put them on. They are collected on a real, unsaved CampaignAdSet
     * rather than in an array, so the casts, the dates and the decimals behave
     * exactly as they will once it is persisted.
     */
    private ?CampaignAdSet $stagedAdSet = null;

    public static function bootHasAdSets(): void
    {
        // Every campaign has an ad set from the moment it exists. Making it
        // lazily on first read would mean a read that writes, and making it on
        // first write would leave a campaign that was never targeted without
        // one at publish time.
        static::created(function (self $campaign): void {
            $campaign->createFirstAdSet();
        });

        static::saved(function (self $campaign): void {
            $campaign->saveAdSetChanges();
        });
    }

    /** @return HasMany<CampaignAdSet, $this> */
    public function adSets(): HasMany
    {
        return $this->hasMany(CampaignAdSet::class)->orderBy('position')->orderBy('id');
    }

    /**
     * The first ad set: the one the campaign's own attributes address.
     *
     * A relation rather than a query, so repeated reads of $campaign->budget
     * cost one lookup instead of one each.
     *
     * @return HasOne<CampaignAdSet, $this>
     */
    public function primaryAdSet(): HasOne
    {
        return $this->hasOne(CampaignAdSet::class)->ofMany([
            'position' => 'min',
            'id' => 'min',
        ]);
    }

    /** Whether this field is the ad set's to answer for this campaign. */
    public function adSetOwns(string $key): bool
    {
        return in_array($key, self::OWNED_BY_AD_SET, true);
    }

    /**
     * This campaign's own stated amount, with no brief fallback.
     *
     * The gate sums these across a brief's campaigns to catch an
     * over-allocation, and the brief asks which campaigns are still unfunded.
     * Both need the campaign's own answer: reading through the ordinary
     * accessor counts the brief's total once per platform, and an unsplit
     * budget then looks perfectly balanced.
     *
     * Named rather than reading getAttributes()['budget'] at the call site,
     * which is what both did before. The raw read is the whole point - the
     * accessor is where the brief fallback happens - and a name says so.
     */
    public function ownBudget(): ?float
    {
        $raw = $this->getAttributes()['budget'] ?? null;

        return $raw === null ? null : (float) $raw;
    }

    /** Where a read of an ad-set-owned field comes from, if anywhere yet. */
    private function adSetForReading(): ?CampaignAdSet
    {
        if ($this->stagedAdSet !== null) {
            return $this->stagedAdSet;
        }

        // Guarded, because the relation on an unsaved campaign would query for
        // campaign_id null and quietly match another campaign's ad set.
        return $this->exists ? $this->primaryAdSet : null;
    }

    /** Where a write of an ad-set-owned field goes. */
    private function adSetForWriting(): CampaignAdSet
    {
        if ($this->exists && ($existing = $this->primaryAdSet) !== null) {
            return $existing;
        }

        return $this->stagedAdSet ??= new CampaignAdSet;
    }

    /**
     * Resolve an ad-set-owned read, or null when there is nothing to read from.
     *
     * Goes through the ad set's own getAttribute so its casts apply: locations
     * comes back an array and starts_at a Carbon instance, whether it was just
     * set in memory or loaded from the row.
     */
    private function adSetAttribute(string $key): mixed
    {
        return $this->adSetForReading()?->getAttribute($key);
    }

    private function createFirstAdSet(): void
    {
        $adSet = $this->stagedAdSet ?? new CampaignAdSet;

        $adSet->campaign_id = $this->getKey();
        $adSet->position = 1;
        $adSet->name = $adSet->name ?: $this->name.' - ad set';

        $adSet->save();

        // Cleared and promoted in one step: from here on the row is the home,
        // and a stale staging instance would shadow it on every read.
        $this->stagedAdSet = null;
        $this->setRelation('primaryAdSet', $adSet);
    }

    /**
     * Persist whatever was written to the ad set alongside the campaign.
     *
     * Also covers the campaign that somehow has no ad set - one inserted
     * without events, or a row from before this existed - by creating it here
     * rather than silently dropping the write.
     */
    private function saveAdSetChanges(): void
    {
        if ($this->stagedAdSet !== null) {
            $this->createFirstAdSet();

            return;
        }

        $adSet = $this->relationLoaded('primaryAdSet')
            ? $this->getRelation('primaryAdSet')
            : null;

        if ($adSet instanceof CampaignAdSet && $adSet->isDirty()) {
            $adSet->save();
        }
    }
}
