<?php

declare(strict_types=1);

namespace app\common\model;

use support\think\Model;

/**
 * 积分商城业务配置（含 PlayX 比例等）
 */
class MallBusinessConfig extends Model
{
    protected string $name = 'mall_business_config';

    protected bool $autoWriteTimestamp = true;

    public const DEFAULT_RETURN_RATIO = 0.1;
    public const DEFAULT_UNLOCK_RATIO = 0.1;
    public const DEFAULT_POINTS_TO_CASH_RATIO = 0.1;
    public const DEFAULT_LIFETIME_POINTS_RATIO = 0.1;

    protected array $type = [
        'create_time'                 => 'integer',
        'update_time'                 => 'integer',
        'return_ratio'                => 'float',
        'unlock_ratio'                => 'float',
        'points_to_cash_ratio'        => 'float',
        'daily_points_enabled'          => 'integer',
        'lifetime_points_enabled'       => 'integer',
        'lifetime_points_ratio'         => 'float',
        'mall_open_date'                => 'string',
        'mall_open_date_previous'       => 'string',
        'mall_open_date_effective_on' => 'string',
    ];

    /**
     * 保证存在一条商城参数配置（比例仅来自后台 mall_business_config，不再读 .env）
     */
    public static function ensureRow(): self
    {
        $row = self::order('id', 'asc')->find();
        if ($row) {
            return $row;
        }

        $now = time();
        $created = self::create([
            'return_ratio'              => self::DEFAULT_RETURN_RATIO,
            'unlock_ratio'              => self::DEFAULT_UNLOCK_RATIO,
            'points_to_cash_ratio'      => self::DEFAULT_POINTS_TO_CASH_RATIO,
            'daily_points_enabled'      => 1,
            'lifetime_points_enabled'   => 0,
            'lifetime_points_ratio'     => self::DEFAULT_LIFETIME_POINTS_RATIO,
            'create_time'               => $now,
            'update_time'               => $now,
        ]);
        if (!$created) {
            throw new \RuntimeException('Failed to create mall_business_config');
        }

        return $created;
    }
}
