<?php

namespace App\Services\Promotions\Placement;

use App\Models\Configuration;
use Illuminate\Support\Facades\Log;
use RuntimeException;

class PromotionSectionCapacityService
{
    public const CONFIG_KEY = 'promotion.section_capacity';
    public const DEFAULT_CAPACITY = 20;

    public function capacity(): array
    {
        $raw = Configuration::getConfigValueByKey(self::CONFIG_KEY);
        $usedDefault = false;

        if ($raw === null || trim((string) $raw) === '') {
            $usedDefault = true;
            Log::warning('Missing promotion section capacity configuration; using fallback.', [
                'config_key' => self::CONFIG_KEY,
                'fallback' => self::DEFAULT_CAPACITY,
            ]);
            $value = self::DEFAULT_CAPACITY;
        } elseif (!ctype_digit((string) $raw)) {
            throw new RuntimeException('promotion.section_capacity must be a positive integer.');
        } else {
            $value = (int) $raw;
        }

        if ($value <= 0) {
            throw new RuntimeException('promotion.section_capacity must be greater than zero.');
        }

        return [
            'key' => self::CONFIG_KEY,
            'value' => $value,
            'used_default' => $usedDefault,
            'warnings' => $usedDefault ? ['promotion.section_capacity missing; fallback capacity 20 used.'] : [],
        ];
    }
}
