<?php

namespace App\Models;

use App\Services\Billing\PlanCatalogue;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use RuntimeException;

class Subscription extends Model
{
    use HasFactory;
    use HasUuids;

    public const TERM_MONTHLY = 'monthly';

    public const TERM_YEARLY = 'yearly';

    /**
     * The conditions the customer is owed. Changing any of these after the fact
     * would rewrite a contract, so the model refuses — a price rise applies to
     * new subscriptions, never to existing ones.
     */
    public const FROZEN = [
        'plan', 'plan_version_id', 'term', 'price_cents', 'currency', 'quota_gb', 'traffic_gb',
        'seats', 'ram_mb', 'cores', 'disk_gb', 'performance', 'tier', 'started_at',
    ];

    protected $guarded = [];

    protected static function booted(): void
    {
        static::updating(function (self $subscription) {
            $frozen = array_intersect(array_keys($subscription->getDirty()), self::FROZEN);

            if ($frozen !== []) {
                throw new RuntimeException(
                    'A subscription snapshot is immutable; tried to change: '.implode(', ', $frozen).
                    '. Cancel this subscription and start a new one instead.'
                );
            }
        });
    }

    protected function casts(): array
    {
        return [
            'price_cents' => 'integer',
            'quota_gb' => 'integer',
            'traffic_gb' => 'integer',
            'seats' => 'integer',
            'ram_mb' => 'integer',
            'cores' => 'integer',
            'disk_gb' => 'integer',
            'template_vmid' => 'integer',
            'tier' => 'integer',
            'started_at' => 'datetime',
            'current_period_start' => 'datetime',
            'current_period_end' => 'datetime',
            'pending_effective_at' => 'datetime',
            'cancelled_at' => 'datetime',
            'stripe_event_at' => 'datetime',
            'granted_at' => 'datetime',
            'granted_until' => 'datetime',
            'catalogue_price_cents' => 'integer',
        ];
    }

    public function uniqueIds(): array
    {
        return ['uuid'];
    }

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

    /** The operator who gave this away, when it was a grant. */
    public function grantedBy(): BelongsTo
    {
        return $this->belongsTo(Operator::class, 'granted_by');
    }

    /**
     * Whether this contract's own terms were set by a grant rather than a
     * purchase — the one fact Revenue and IssueInvoice both key off.
     */
    public function isGranted(): bool
    {
        return $this->granted_at !== null;
    }

    /** A full gift: nothing was charged for it at all. */
    public function isFreeGrant(): bool
    {
        return $this->isGranted() && (int) $this->price_cents === 0;
    }

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

    /** Which version of the plan this contract was sold under. */
    public function planVersion(): BelongsTo
    {
        return $this->belongsTo(PlanVersion::class, 'plan_version_id');
    }

    /** Modules booked onto this contract, each frozen at its booked price. */
    public function addons(): HasMany
    {
        return $this->hasMany(SubscriptionAddon::class);
    }

    /** Every commercial event this contract has been through. */
    public function records(): HasMany
    {
        return $this->hasMany(SubscriptionRecord::class);
    }

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

    /** Whether the catalogue still sells this plan at all. */
    public static function knowsPlan(string $plan): bool
    {
        return app(PlanCatalogue::class)->isSellable($plan);
    }

    /** The single currency every catalogue price is expressed in. */
    public static function catalogueCurrency(): string
    {
        return strtoupper((string) config('provisioning.currency', 'EUR'));
    }

    /**
     * Take the version on sale right now and freeze it onto a new subscription.
     *
     * Reads the catalogue tables, never config: there is one source, and it is
     * the one the owner can actually edit. An unknown, withdrawn or unpriced
     * plan throws rather than returning something plausible — a contract opened
     * from a guess is worse than a purchase that visibly fails.
     */
    public static function snapshotFrom(string $plan, string $term = self::TERM_MONTHLY, ?int $versionId = null): array
    {
        // A typo would otherwise be priced monthly while carrying an unknown
        // term — a subscription whose price and billing period disagree.
        if (! in_array($term, [self::TERM_MONTHLY, self::TERM_YEARLY], true)) {
            throw new RuntimeException("Unknown term: {$term}");
        }

        // Honour the version the customer was actually shown, even if it has
        // stopped being sold since — a checkout that completes just after a
        // scheduled transition must not contract them to terms they never saw.
        $version = $versionId !== null
            ? app(PlanCatalogue::class)->soldVersion($plan, $versionId)
            : app(PlanCatalogue::class)->currentVersion($plan);
        $price = $version->priceFor($term);

        if ($price === null) {
            throw new RuntimeException("Plan '{$plan}' is not sold on a {$term} term.");
        }

        return [
            'plan' => $plan,
            // Which version this contract was sold under. A historical
            // reference resolved by plan NAME would hand back today's terms.
            'plan_version_id' => $version->id,
            'term' => $term,
            'price_cents' => $price->amount_cents,
            'currency' => $price->currency,
            'quota_gb' => $version->quota_gb,
            'traffic_gb' => $version->traffic_gb,
            'seats' => $version->seats,
            'ram_mb' => $version->ram_mb,
            'cores' => $version->cores,
            'disk_gb' => $version->disk_gb,
            'performance' => $version->performance,
            // Copied so provisioning never has to ask the catalogue what to
            // clone. Not in FROZEN — see the migration for why.
            'template_vmid' => $version->template_vmid,
            // Frozen too: which direction a later change goes must not depend
            // on where the plan sits in today's catalogue.
            'tier' => (int) $version->family->tier,
        ];
    }

    public function isYearly(): bool
    {
        return $this->term === self::TERM_YEARLY;
    }

    /**
     * What this contract works out to per month.
     *
     * `price_cents` is the price of a TERM, and a yearly term holds the whole
     * year. Everything that prints a monthly figure — the plan card, the cloud
     * page, the revenue column — has to divide, and every one of them getting
     * it right separately is not something to rely on.
     */
    public function monthlyPriceCents(): int
    {
        return $this->isYearly()
            ? (int) round($this->price_cents / 12)
            : (int) $this->price_cents;
    }

    /**
     * The whole monthly bill, net: the plan plus every module still booked.
     *
     * All of it frozen — that is the owner's rule. A total assembled from the
     * contract for the plan and from today's catalogue for the modules would
     * protect half a customer's price and quietly re-price the other half.
     */
    public function totalMonthlyCents(): int
    {
        return $this->monthlyPriceCents() + $this->addons
            ->where('cancelled_at', null)
            ->sum(fn (SubscriptionAddon $addon) => $addon->monthlyCents());
    }
}
