<?php

namespace WPSN\Modules\Notifications;

defined('ABSPATH') || exit;

final class NotificationsInstaller
{
    private const OPTION_NAME = 'wpsn_notifications_db_version';
    private const CURRENT_VERSION = '1';

    public static function maybeInstall(): void
    {
        $v = get_option(self::OPTION_NAME, '');
        $v = is_string($v) ? $v : '';
        if ($v === self::CURRENT_VERSION) {
            return;
        }

        self::install();
        update_option(self::OPTION_NAME, self::CURRENT_VERSION, false);
    }

    public static function install(): void
    {
        global $wpdb;
        $table = $wpdb->prefix . 'wpsn_notifications';

        $charset = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE {$table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            created_at datetime NOT NULL,
            source varchar(50) NOT NULL DEFAULT '',
            type varchar(50) NOT NULL DEFAULT '',
            severity varchar(12) NOT NULL DEFAULT 'info',
            event_key varchar(191) NOT NULL DEFAULT '',
            title varchar(191) NOT NULL DEFAULT '',
            message text NOT NULL,
            url varchar(255) NOT NULL DEFAULT '',
            meta longtext NULL,
            acknowledged_at datetime NULL,
            muted_until datetime NULL,
            sent_at datetime NULL,
            send_attempts int(10) unsigned NOT NULL DEFAULT 0,
            last_error text NULL,
            PRIMARY KEY  (id),
            UNIQUE KEY event_key (event_key),
            KEY created_at (created_at),
            KEY source (source),
            KEY severity (severity),
            KEY acknowledged_at (acknowledged_at),
            KEY muted_until (muted_until),
            KEY sent_at (sent_at)
        ) {$charset};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }
}
