<?php

namespace App\Models;

use App\Campaigns\CampaignImporter;
use App\Models\Concerns\HasAdSets;
use App\Models\Concerns\ResolvesFromBrief;
use App\Support\CurrencyMinorUnits;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

#[Fillable([
    'user_id', 'brief_id', 'name', 'platform', 'campaign_type', 'youtube_video_id', 'objective', 'special_ad_categories', 'budget', 'budget_level',
    'budget_mode', 'currency', 'status',
    'audience', 'locations', 'placements', 'schedule', 'external_campaign_id', 'meta',
    'landing_url', 'utm', 'ad_account_id', 'page_id', 'instagram_account_id', 'pixel_id', 'conversion_event',
    'optimization_goal',
    'bid_strategy', 'bid_amount', 'external_ids', 'last_error',
    'starts_at', 'ends_at', 'published_state', 'activated_at', 'last_synced_at',
])]
class Campaign extends Model
{
    use HasAdSets, ResolvesFromBrief;

    protected function casts(): array
    {
        return [
            'special_ad_categories' => 'array',
            'schedule' => 'array',
            'meta' => 'array',
            'external_ids' => 'array',
            'published_state' => 'array',
            'activated_at' => 'datetime',
            'last_synced_at' => 'datetime',
            'budget' => 'decimal:2',
            'bid_amount' => 'decimal:2',
            // locations, audience, placements, starts_at and ends_at are cast on
            // CampaignAdSet, which is where they live now. Declaring them here
            // as well would be a second place to keep in step, for values this
            // model no longer stores.
        ];
    }

    /**
     * Where a field lives, then what the brief says if it is still unanswered.
     *
     * Two layers, in this order, and the order is the whole point. The field's
     * home comes first - the ad set for targeting, dates and the bid; the
     * campaign for everything else - and only a home with no answer asks the
     * brief. Reversed, a brief's landing page would beat the ad set's own
     * targeting; collapsed into one step, an ad set's budget would never be
     * consulted at all.
     *
     * Both layers were a getAttribute() override in their own trait, which PHP
     * will not let a class use together, so the composition lives here where it
     * can be read rather than inferred from trait ordering.
     *
     * @param  string  $key
     */
    public function getAttribute($key): mixed
    {
        $value = $this->adSetOwns($key)
            ? $this->adSetAttribute($key)
            : parent::getAttribute($key);

        return $this->briefFallback($key, $value);
    }

    /**
     * @param  string  $key
     * @param  mixed  $value
     */
    public function setAttribute($key, $value): mixed
    {
        if (! $this->adSetOwns($key)) {
            return parent::setAttribute($key, $value);
        }

        $this->adSetForWriting()->setAttribute($key, $value);

        return $this;
    }

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

    /**
     * What this campaign is advertising, shared with every other platform.
     *
     * Null for an adopted campaign. Those are real campaigns already running on
     * the platform, pulled in by {@see CampaignImporter} so a
     * buyer can edit them here; they arrive carrying their own objective,
     * budget, bidding, schedule and targeting, and never had a brief. Editing
     * one must work with no brief at all, which is why nothing may assume this
     * is present.
     */
    public function brief(): BelongsTo
    {
        return $this->belongsTo(Brief::class);
    }

    public function targetingSet(): HasOne
    {
        return $this->hasOne(TargetingSet::class);
    }

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

    /** The ads assembled in chat: an asset plus the words around it. */
    public function ads(): HasMany
    {
        return $this->hasMany(CampaignAd::class);
    }

    /** Changes pushed to this campaign since it went live. */
    public function changes(): HasMany
    {
        return $this->hasMany(CampaignChange::class);
    }

    /** Reads of this campaign's live structure, successful or not. */
    public function syncRuns(): HasMany
    {
        return $this->hasMany(CampaignSyncRun::class);
    }

    /** The most recent read attempt, whatever its outcome. */
    public function latestSyncRun(): HasOne
    {
        return $this->hasOne(CampaignSyncRun::class)->latestOfMany();
    }

    /** The most recent read that produced a usable snapshot. */
    public function latestSuccessfulSyncRun(): HasOne
    {
        return $this->hasOne(CampaignSyncRun::class)->ofMany(
            ['id' => 'max'],
            fn ($query) => $query->whereIn('status', [CampaignSyncRun::Succeeded, CampaignSyncRun::Partial]),
        );
    }

    /** What the platform last confirmed this campaign is made of. */
    public function platformEntities(): HasMany
    {
        return $this->hasMany(CampaignPlatformEntity::class);
    }

    /** Differences between successive platform reads. */
    public function platformDrifts(): HasMany
    {
        return $this->hasMany(CampaignPlatformDrift::class);
    }

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

    /**
     * Whether this campaign exists on the platform.
     *
     * Called isLive() until now, which read as "is running" and never meant it:
     * all twelve call sites want "has been published", and a published campaign is
     * built paused on every platform. The name was one careless reading away from
     * gating a spend decision on the wrong question.
     */
    public function isPublished(): bool
    {
        return filled($this->external_campaign_id);
    }

    /**
     * Whether it is actually running, which is a different question.
     *
     * Publishing builds a campaign and parks it - PAUSED on Meta and Google, DRAFT
     * on LinkedIn - and it starts only when somebody asks for it in the chat and
     * approves it. Until then this is false and nothing is being spent.
     */
    public function isRunning(): bool
    {
        return $this->isPublished() && $this->activated_at !== null;
    }

    /**
     * Where the budget sits and what kind it is.
     *
     * Null means nobody was asked, which is read as the ordinary arrangement
     * every campaign so far used: one daily amount, held on the ad set. Read
     * through these rather than off the columns, so the fallback is in one place.
     */
    public function budgetLevel(): string
    {
        return $this->budget_level ?: 'adset';
    }

    public function budgetMode(): string
    {
        return $this->budget_mode ?: 'daily';
    }

    /** Whether Meta holds the budget on the campaign and moves it between ad sets. */
    public function usesCampaignBudget(): bool
    {
        return $this->budgetLevel() === 'campaign';
    }

    /** A total to be spent by the end date, rather than an amount per day. */
    public function usesLifetimeBudget(): bool
    {
        return $this->budgetMode() === 'lifetime';
    }

    /**
     * Meta takes money in minor units, always as an integer.
     *
     * The factor is the currency's, not a hardcoded 100. The yen has no
     * subunit, so a 3000 budget on a JPY account was being sent as 300000.
     */
    public function budgetInMinorUnits(): int
    {
        return CurrencyMinorUnits::toMinor($this->budget, $this->currency);
    }

    /** The bid, in the same units and by the same rule. */
    public function bidInMinorUnits(): ?int
    {
        return $this->bid_amount === null
            ? null
            : CurrencyMinorUnits::toMinor($this->bid_amount, $this->currency);
    }
}
