CREATE TABLE IF NOT EXISTS allegro_integration_settings (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    environment VARCHAR(16) NOT NULL DEFAULT 'sandbox',
    client_id VARCHAR(128) NULL,
    client_secret_encrypted TEXT NULL,
    redirect_uri VARCHAR(255) NULL,
    orders_fetch_enabled TINYINT(1) NOT NULL DEFAULT 0,
    orders_fetch_start_date DATE NULL,
    access_token_encrypted MEDIUMTEXT NULL,
    refresh_token_encrypted MEDIUMTEXT NULL,
    token_type VARCHAR(32) NULL,
    token_scope VARCHAR(255) NULL,
    token_expires_at DATETIME NULL,
    connected_at DATETIME NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY allegro_integration_settings_environment_idx (environment),
    KEY allegro_integration_settings_token_expires_at_idx (token_expires_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO allegro_integration_settings (
    id, environment, client_id, client_secret_encrypted, redirect_uri, orders_fetch_enabled,
    orders_fetch_start_date, access_token_encrypted, refresh_token_encrypted, token_type, token_scope,
    token_expires_at, connected_at, created_at, updated_at
)
VALUES (
    1, 'sandbox', NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NOW(), NOW()
)
ON DUPLICATE KEY UPDATE
    updated_at = VALUES(updated_at);
