-- OTP storage schema
-- Import once: mysql -u root -p < schema.sql

CREATE DATABASE IF NOT EXISTS mocargo_otp
  CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

USE mocargo_otp;

CREATE TABLE IF NOT EXISTS otp_codes (
  id          BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  phone       VARCHAR(20)  NOT NULL,
  otp_hash    VARCHAR(255) NOT NULL,           -- password_hash() of the code
  expires_at  DATETIME     NOT NULL,
  attempts    INT UNSIGNED NOT NULL DEFAULT 0, -- wrong verify attempts
  consumed    TINYINT(1)   NOT NULL DEFAULT 0, -- 1 once used/invalidated
  verified_at DATETIME     NULL,
  created_at  DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_phone (phone),
  INDEX idx_phone_consumed (phone, consumed),
  INDEX idx_created (created_at)
) ENGINE=InnoDB;
