CREATE TABLE IF NOT EXISTS otp (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id VARCHAR(255) NOT NULL,
    openid VARCHAR(255) NOT NULL,
    name VARCHAR(100) NOT NULL,
    issuer VARCHAR(255),
    secret VARCHAR(255) NOT NULL,
    algorithm VARCHAR(10) NOT NULL DEFAULT 'SHA1',
    digits INTEGER NOT NULL DEFAULT 6,
    period INTEGER NOT NULL DEFAULT 30,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(user_id, name),
    UNIQUE(openid)
);

-- Add index for faster lookups
CREATE INDEX IF NOT EXISTS idx_otp_user_id ON otp(user_id);
CREATE INDEX IF NOT EXISTS idx_otp_openid ON otp(openid);

-- Trigger to update the updated_at timestamp
CREATE TRIGGER IF NOT EXISTS update_otp_timestamp 
    AFTER UPDATE ON otp
BEGIN
    UPDATE otp SET updated_at = CURRENT_TIMESTAMP WHERE id = NEW.id;
END;