<?php

namespace App\Domain\Financial\Support;

use App\Domain\Financial\Models\FinancialAccount;

/**
 * One credit in the entry a collection produces: an account and the piasters
 * that land in it, with the rule that put them there.
 *
 * The provenance is not decoration. When the finance manager asks why five
 * pounds of a subscription ended up in 4010, the answer has to be readable off
 * the transaction row itself — not reconstructed from whatever the rules happen
 * to say today, months after the rule was edited.
 */
final class RevenuePosting
{
    /** @param list<string> $ruleLabels */
    public function __construct(
        public readonly FinancialAccount $account,
        public readonly int $amount,
        public readonly string $kind,           // 'revenue' | 'tax'
        public readonly array $ruleLabels = [],
        public readonly ?int $mappingId = null,
        public readonly ?int $mappingLineId = null,
        public readonly ?string $sourceKey = null,
    ) {}

    public function isTax(): bool
    {
        return $this->kind === 'tax';
    }

    public function withAmount(int $amount): self
    {
        return new self(
            $this->account,
            $amount,
            $this->kind,
            $this->ruleLabels,
            $this->mappingId,
            $this->mappingLineId,
            $this->sourceKey,
        );
    }

    /** What gets written into `transactions.metadata` for the audit trail. */
    public function metadata(): array
    {
        return array_filter([
            'routing_kind' => $this->kind,
            'routing_source' => $this->sourceKey,
            'routing_mapping_id' => $this->mappingId,
            'routing_line_id' => $this->mappingLineId,
            'routing_rules' => $this->ruleLabels ?: null,
        ], fn ($v) => $v !== null);
    }
}
