-- name: GetConfig :one
SELECT * FROM config LIMIT 1;

-- name: UpsertConfig :exec
INSERT INTO config (api_token, zone_id, domain, update_period)
VALUES (?, ?, ?, ?)
ON CONFLICT DO UPDATE SET
    api_token = excluded.api_token,
    zone_id = excluded.zone_id,
    domain = excluded.domain,
    update_period = excluded.update_period;

-- name: InitSchema :exec
-- This query is used to ensure the schema is set up properly
CREATE TABLE IF NOT EXISTS config (
    api_token TEXT,
    zone_id TEXT,
    domain TEXT NOT NULL DEFAULT 'mz.uy',
    update_period TEXT NOT NULL DEFAULT '0 */6 * * *'
);

CREATE TRIGGER IF NOT EXISTS enforce_single_config
BEFORE INSERT ON config
WHEN (SELECT COUNT(*) FROM config) > 0
BEGIN
    SELECT RAISE(FAIL, 'Only one config record allowed');
END;

-- Insert default config if none exists
INSERT OR IGNORE INTO config (domain, update_period)
SELECT 'mz.uy', '0 */6 * * *'
WHERE NOT EXISTS (SELECT 1 FROM config);
