-- ============================================
-- Flash Call OTP System — Database Setup
-- Domain: otp.intaleqapp.com
-- ============================================

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

USE otpDb;

-- OTP Requests Table
CREATE TABLE IF NOT EXISTS otp_requests (
    id INT AUTO_INCREMENT PRIMARY KEY,
    phone VARCHAR(20) NOT NULL,
    otp_code VARCHAR(6) NOT NULL,
    caller_id VARCHAR(20) NOT NULL DEFAULT '',
    status ENUM('pending','pending_sms','pending_whatsapp','calling','completed','failed','expired','verified') NOT NULL DEFAULT 'pending',
    method ENUM('flash_call','sms','whatsapp','telegram') NOT NULL DEFAULT 'flash_call',
    device_id VARCHAR(50) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP,
    expires_at TIMESTAMP NOT NULL,
    verified_at TIMESTAMP NULL,
    INDEX idx_phone (phone),
    INDEX idx_status (status),
    INDEX idx_method_status (method, status),
    INDEX idx_device_id (device_id),
    INDEX idx_expires (expires_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Caller Devices Table
CREATE TABLE IF NOT EXISTS caller_devices (
    id INT AUTO_INCREMENT PRIMARY KEY,
    device_id VARCHAR(50) UNIQUE NOT NULL,
    phone_number VARCHAR(20) NOT NULL,
    sim_slot TINYINT DEFAULT 0,
    is_active BOOLEAN DEFAULT TRUE,
    last_seen TIMESTAMP NULL,
    calls_today INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_active (is_active),
    INDEX idx_calls_today (calls_today)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- API Request Logs Table
CREATE TABLE IF NOT EXISTS api_logs (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    endpoint VARCHAR(50) NOT NULL,
    method VARCHAR(10) NOT NULL,
    ip_address VARCHAR(45) NOT NULL,
    user_agent VARCHAR(500) NULL,
    request_body TEXT NULL,
    response_code SMALLINT NOT NULL DEFAULT 200,
    error VARCHAR(500) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_endpoint (endpoint),
    INDEX idx_created (created_at),
    INDEX idx_ip (ip_address)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ============================================
-- Scheduled Cleanup (add to MySQL Event Scheduler)
-- ============================================

-- Enable event scheduler
SET GLOBAL event_scheduler = ON;

-- Expire old pending requests every 30 seconds
DELIMITER //
CREATE EVENT IF NOT EXISTS expire_otp_requests
ON SCHEDULE EVERY 30 SECOND
DO
BEGIN
    UPDATE otp_requests
    SET status = 'expired', updated_at = NOW()
    WHERE status IN ('pending', 'pending_sms', 'calling')
      AND expires_at < NOW();
END //
DELIMITER ;

-- Reset calls_today counter daily at midnight (Asia/Amman = UTC+3)
DELIMITER //
CREATE EVENT IF NOT EXISTS reset_daily_calls
ON SCHEDULE EVERY 1 DAY
STARTS CONCAT(CURDATE() + INTERVAL 1 DAY, ' 00:00:00')
DO
BEGIN
    UPDATE caller_devices SET calls_today = 0;
END //
DELIMITER ;

-- Clean up old API logs (older than 30 days)
DELIMITER //
CREATE EVENT IF NOT EXISTS cleanup_api_logs
ON SCHEDULE EVERY 1 DAY
STARTS CONCAT(CURDATE() + INTERVAL 1 DAY, ' 03:00:00')
DO
BEGIN
    DELETE FROM api_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY);
END //
DELIMITER ;

-- ============================================
-- Grant permissions
-- ============================================
-- Run this separately with root access:
-- GRANT SELECT, INSERT, UPDATE, DELETE ON otpDb.* TO 'otpUser'@'localhost' IDENTIFIED BY 'STRONG_PASSWORD';
-- FLUSH PRIVILEGES;
sfvo055OJV7VqPW25VEQ