<?php

namespace App\Services\Mail;

use App\Models\Setting;
use Illuminate\Support\Arr;

class AgencyManagementMailSettingsManager
{
    public const GROUP = 'agency_management_mail';

    /**
     * @return array<string, mixed>
     */
    public function all(): array
    {
        $stored = Setting::where('group', self::GROUP)
            ->get()
            ->mapWithKeys(fn (Setting $setting) => [$setting->key => $setting->value])
            ->all();

        return array_merge($this->defaults(), $stored, [
            'auto_weekly_enabled' => $this->bool($stored['auto_weekly_enabled'] ?? true),
            'auto_monthly_enabled' => $this->bool($stored['auto_monthly_enabled'] ?? true),
            'include_html' => $this->bool($stored['include_html'] ?? true),
            'include_csv' => $this->bool($stored['include_csv'] ?? true),
        ]);
    }

    /**
     * @param array<string, mixed> $data
     */
    public function save(array $data): void
    {
        $allowed = [
            'recipients',
            'cc',
            'bcc',
            'subject_prefix',
            'intro_note',
            'auto_weekly_enabled',
            'auto_monthly_enabled',
            'include_html',
            'include_csv',
        ];

        foreach ($allowed as $key) {
            $value = Arr::get($data, $key);

            if (in_array($key, ['auto_weekly_enabled', 'auto_monthly_enabled', 'include_html', 'include_csv'], true)) {
                $value = $value ? '1' : '0';
            }

            Setting::updateOrCreate(
                ['group' => self::GROUP, 'key' => $key],
                ['value' => $value, 'is_encrypted' => false]
            );
        }
    }

    public function autoEnabled(string $period): bool
    {
        $settings = $this->all();

        return match ($period) {
            'monthly' => (bool) $settings['auto_monthly_enabled'],
            'weekly' => (bool) $settings['auto_weekly_enabled'],
            default => true,
        };
    }

    /**
     * @return array<string, mixed>
     */
    private function defaults(): array
    {
        return [
            'recipients' => '',
            'cc' => '',
            'bcc' => '',
            'subject_prefix' => 'DW Ads Reporter',
            'intro_note' => 'Ajans operasyon ve müşteri sağlık özeti ektedir.',
            'auto_weekly_enabled' => true,
            'auto_monthly_enabled' => true,
            'include_html' => true,
            'include_csv' => true,
        ];
    }

    private function bool(mixed $value): bool
    {
        if (is_bool($value)) {
            return $value;
        }

        return in_array((string) $value, ['1', 'true', 'on', 'yes'], true);
    }
}
