<?php

namespace App\Models;

use App\Campaigns\CampaignImporter;
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 ResolvesFromBrief;

    protected function casts(): array
    {
        return [
            'special_ad_categories' => 'array',
            'audience' => 'array',
            'locations' => 'array',
            'placements' => 'array',
            'schedule' => 'array',
            'meta' => 'array',
            'external_ids' => 'array',
            'published_state' => 'array',
            'activated_at' => 'datetime',
            'starts_at' => 'datetime',
            'ends_at' => 'datetime',
            'last_synced_at' => 'datetime',
            'budget' => 'decimal:2',
            'bid_amount' => 'decimal:2',
        ];
    }

    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);
    }

    /**
     * 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);
    }
}
