<?php

namespace App\Models;

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;

/**
 * One ad set: who to show the ads to, when, and for how much.
 *
 * Meta's own division, which this product used to flatten. A campaign carries
 * the objective, the ad account and the Page; an ad set carries the targeting,
 * the schedule, the optimisation goal and - unless the campaign holds the money
 * itself - the budget and the bid. The ads hang off the ad set, not the
 * campaign.
 *
 * Everything here was a column on campaigns, which worked only because there
 * was always exactly one ad set. A second one had nowhere to put its targeting,
 * so adding one was impossible and an adopted campaign's extra ad sets were
 * "recorded, not managed".
 *
 * The currency is deliberately not here. It belongs to the ad account, so two
 * ad sets under one campaign cannot disagree about it, and reading it off the
 * campaign keeps BudgetCeiling asking one object about one currency.
 */
#[Fillable([
    'campaign_id', 'position', 'name',
    'locations', 'audience', 'placements',
    'optimization_goal', 'conversion_event',
    'budget', 'budget_mode', 'bid_strategy', 'bid_amount',
    'starts_at', 'ends_at',
    'external_adset_id', 'status', 'last_error',
])]
class CampaignAdSet extends Model
{
    protected function casts(): array
    {
        return [
            'locations' => 'array',
            'audience' => 'array',
            'placements' => 'array',
            'starts_at' => 'datetime',
            'ends_at' => 'datetime',
            'budget' => 'decimal:2',
            'bid_amount' => 'decimal:2',
        ];
    }

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

    /** The ads in this ad set. */
    public function ads(): HasMany
    {
        return $this->hasMany(CampaignAd::class, 'ad_set_id');
    }

    /** Whether this ad set exists on the platform. */
    public function isPublished(): bool
    {
        return filled($this->external_adset_id);
    }

    /**
     * This ad set's own answer about money, or the campaign's when it has none.
     *
     * The four money fields here are overrides. The buyer states one
     * arrangement for the campaign and the ordinary campaign has one ad set
     * following it, so these are normally null; an ad set added later fills
     * them in when the point of adding it was to spend differently.
     */
    public function effectiveBudget(): ?float
    {
        return $this->budget !== null
            ? (float) $this->budget
            : $this->campaign?->ownBudget();
    }

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

    public function effectiveBidStrategy(): string
    {
        return $this->bid_strategy
            ?: ($this->campaign?->bid_strategy ?: 'LOWEST_COST_WITHOUT_CAP');
    }

    public function effectiveBidAmount(): ?float
    {
        $amount = $this->bid_amount ?? $this->campaign?->bid_amount;

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

    /**
     * The money in minor units, by the account's currency rather than a
     * hardcoded 100: the yen has no subunit, so a 3000 budget on a JPY account
     * was being sent as 300000.
     *
     * Null rather than 0 when there is no amount. Zero is an amount, and
     * sending it would be a request to spend nothing.
     */
    public function budgetInMinorUnits(): ?int
    {
        $budget = $this->effectiveBudget();

        return $budget === null
            ? null
            : CurrencyMinorUnits::toMinor($budget, $this->campaign?->currency);
    }

    public function bidInMinorUnits(): ?int
    {
        $bid = $this->effectiveBidAmount();

        return $bid === null
            ? null
            : CurrencyMinorUnits::toMinor($bid, $this->campaign?->currency);
    }

    /** Targeting as the platform wants it, which is one flat payload. */
    public function targeting(): array
    {
        return [
            ...(array) ($this->locations ?? []),
            ...(array) ($this->audience ?? []),
            'placements' => (array) ($this->placements ?? []),
        ];
    }
}
