<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Db;

use JsonSerializable;
use OCP\AppFramework\Db\Entity;

/**
 * Fee rule entity mapping all columns from oc_mv_fee_rules.
 *
 * The family_rules_json column stores a JSON object describing
 * position-based fee overrides, e.g.:
 * {"1": 100.00, "2": 75.00, "3+": 50.00}
 *
 * Part of Issue #42.
 *
 * @method int getYearFrom()
 * @method void setYearFrom(int $yearFrom)
 * @method string getBaseRate()
 * @method void setBaseRate(string $baseRate)
 * @method string getFamilyRulesJson()
 * @method void setFamilyRulesJson(string $familyRulesJson)
 * @method string getInactiveRule()
 * @method void setInactiveRule(string $inactiveRule)
 * @method string getCreatedAt()
 * @method void setCreatedAt(string $createdAt)
 * @method string getCreatedBy()
 * @method void setCreatedBy(string $createdBy)
 */
class FeeRule extends Entity implements JsonSerializable {

    protected int $yearFrom = 0;
    protected string $baseRate = '0.00';
    protected string $familyRulesJson = '{}';
    protected string $inactiveRule = 'freeze_rate_at_exit';
    protected string $createdAt = '';
    protected string $createdBy = '';

    public function __construct() {
        $this->addType('id', 'integer');
        $this->addType('yearFrom', 'integer');
    }

    /**
     * Parse family rules JSON into an associative array.
     *
     * @return array<string, float> e.g. {"1": 100.00, "2": 75.00, "3+": 50.00}
     */
    public function getFamilyRules(): array {
        $decoded = json_decode($this->familyRulesJson, true);
        return is_array($decoded) ? $decoded : [];
    }

    public function jsonSerialize(): array {
        return [
            'id' => $this->id,
            'yearFrom' => $this->yearFrom,
            'baseRate' => $this->baseRate,
            'familyRules' => $this->getFamilyRules(),
            'familyRulesJson' => $this->familyRulesJson,
            'inactiveRule' => $this->inactiveRule,
            'createdAt' => $this->createdAt,
            'createdBy' => $this->createdBy,
        ];
    }
}
