<?php

namespace App\Support;

use App\Contracts\SettingRepositoryContract;
use App\Services\Settings\SettingService;

class NotificationSettings
{
    /**
     * @return array<string, array<string, mixed>>
     */
    public static function events(): array
    {
        return config('notifications.events', []);
    }

    /**
     * @return list<string>
     */
    public static function eventKeys(): array
    {
        return array_keys(self::events());
    }

    public static function label(string $eventKey): string
    {
        return (string) (self::events()[$eventKey]['label'] ?? $eventKey);
    }

    /**
     * @return list<string>
     */
    public static function placeholders(string $eventKey): array
    {
        return self::events()[$eventKey]['placeholders'] ?? [];
    }

    /**
     * @return array<string, mixed>
     */
    public static function defaults(string $eventKey): array
    {
        return self::events()[$eventKey]['defaults'] ?? [];
    }

    public static function settingKey(string $eventKey, string $field): string
    {
        return "notifications.{$eventKey}.{$field}";
    }

    public static function get(string $eventKey, string $field, mixed $default = null): mixed
    {
        $defaults = self::defaults($eventKey);
        $fallback = $defaults[$field] ?? $default;

        return app(SettingService::class)->get(self::settingKey($eventKey, $field), $fallback);
    }

    public static function isEmailEnabled(string $eventKey): bool
    {
        return filter_var(self::get($eventKey, 'email_enabled', true), FILTER_VALIDATE_BOOLEAN);
    }

    public static function isSmsEnabled(string $eventKey): bool
    {
        return filter_var(self::get($eventKey, 'sms_enabled', true), FILTER_VALIDATE_BOOLEAN);
    }

    /**
     * @return array<string, mixed>
     */
    public static function valuesForForm(): array
    {
        $values = [];

        foreach (self::eventKeys() as $eventKey) {
            foreach (['email_enabled', 'email_subject', 'email_body', 'sms_enabled', 'sms_body'] as $field) {
                $values[$eventKey][$field] = self::get($eventKey, $field, self::defaults($eventKey)[$field] ?? '');
            }
        }

        return $values;
    }

    /**
     * @return array<string, array{value: mixed, category: string, type: string}>
     */
    public static function settingsPayload(array $input): array
    {
        $payload = [];

        foreach (self::eventKeys() as $eventKey) {
            $prefix = "notifications.{$eventKey}";
            $payload["{$prefix}.email_enabled"] = [
                'value' => ! empty($input[$eventKey]['email_enabled']) ? '1' : '0',
                'category' => 'notifications',
                'type' => 'boolean',
            ];
            $payload["{$prefix}.email_subject"] = [
                'value' => $input[$eventKey]['email_subject'] ?? '',
                'category' => 'notifications',
                'type' => 'string',
            ];
            $payload["{$prefix}.email_body"] = [
                'value' => $input[$eventKey]['email_body'] ?? '',
                'category' => 'notifications',
                'type' => 'string',
            ];
            $payload["{$prefix}.sms_enabled"] = [
                'value' => ! empty($input[$eventKey]['sms_enabled']) ? '1' : '0',
                'category' => 'notifications',
                'type' => 'boolean',
            ];
            $payload["{$prefix}.sms_body"] = [
                'value' => $input[$eventKey]['sms_body'] ?? '',
                'category' => 'notifications',
                'type' => 'string',
            ];
        }

        return $payload;
    }

    /**
     * @return array<string, array{value: mixed, category: string, type: string}>
     */
    public static function defaultSettingsPayload(): array
    {
        $input = [];

        foreach (self::eventKeys() as $eventKey) {
            $defaults = self::defaults($eventKey);
            $input[$eventKey] = [
                'email_enabled' => $defaults['email_enabled'] ?? true,
                'email_subject' => $defaults['email_subject'] ?? '',
                'email_body' => $defaults['email_body'] ?? '',
                'sms_enabled' => $defaults['sms_enabled'] ?? true,
                'sms_body' => $defaults['sms_body'] ?? '',
            ];
        }

        return self::settingsPayload($input);
    }

    public static function seedMissingDefaults(): void
    {
        $repository = app(SettingRepositoryContract::class);

        foreach (self::defaultSettingsPayload() as $key => $config) {
            if ($repository->findByKey($key) !== null) {
                continue;
            }

            $repository->set(
                $key,
                $config['value'] ?? '',
                $config['category'] ?? 'notifications',
                $config['type'] ?? 'string',
            );
        }

        app(SettingService::class)->flushCache();
    }
}
