<?php

namespace Modules\WhatsApp\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class WaSetting extends Model
{
    protected $table = 'wa_settings';
    protected $guarded = ['id'];

    public static function get(int $businessId, string $key, $default = null)
    {
        if (!Schema::hasTable('wa_settings')) {
            return $default;
        }
        $row = DB::table('wa_settings')
            ->where('business_id', $businessId)
            ->where('key', $key)
            ->first();

        return $row ? $row->value : $default;
    }

    public static function set(int $businessId, string $key, $value): void
    {
        if (!Schema::hasTable('wa_settings')) {
            return;
        }
        DB::table('wa_settings')->updateOrInsert(
            ['business_id' => $businessId, 'key' => $key],
            [
                'value'      => is_array($value) ? json_encode($value) : (string) $value,
                'updated_at' => now(),
                'created_at' => now(),
            ]
        );
    }

    public static function allFor(int $businessId): array
    {
        $defaults = array_merge([
            'enabled'          => '1',
            'default_channel'  => '',
            'notify_emails'    => '',
            'opt_out_keyword'  => 'STOP',
            'ai_enabled'       => '0',
            'ai_can_book'      => '0',
            'powered_by'       => '1',
            'low_stock_enabled' => '0',
            'low_stock_number'  => '',
            // Anti-ban pacing (seconds / ms)
            'gap_min'            => (string) config('whatsapp.sending.gap_min', 4),
            'gap_max'            => (string) config('whatsapp.sending.gap_max', 12),
            'typing_per_char_ms' => (string) config('whatsapp.sending.typing_per_char_ms', 55),
            'typing_min_ms'      => (string) config('whatsapp.sending.typing_min_ms', 900),
            'typing_max_ms'      => (string) config('whatsapp.sending.typing_max_ms', 9000),
        ], \Modules\WhatsApp\Entities\Services\WaEvents::settingDefaults());

        if (!Schema::hasTable('wa_settings')) {
            return $defaults;
        }

        $stored = DB::table('wa_settings')
            ->where('business_id', $businessId)
            ->pluck('value', 'key')
            ->toArray();

        return array_merge($defaults, $stored);
    }
}
