/**
 * SMS Verification Service
 * Handles phone number verification via OTP during signup
 */

import twilio from "twilio";
import { db } from "../db.ts";
import { users } from "../../drizzle/schema.ts";
import { eq } from "drizzle-orm";

const twilioClient = twilio(
  process.env.TWILIO_ACCOUNT_SID,
  process.env.TWILIO_AUTH_TOKEN
);

export interface SMSVerificationRequest {
  phoneNumber: string;
  userId?: number;
}

export interface SMSVerificationResponse {
  success: boolean;
  message: string;
  verificationSid?: string;
}

export interface VerifyOTPRequest {
  phoneNumber: string;
  otp: string;
  userId?: number;
}

export interface VerifyOTPResponse {
  success: boolean;
  message: string;
  verified?: boolean;
}

/**
 * Send OTP to phone number via SMS
 */
export const sendSMSVerification = async (
  phoneNumber: string
): Promise<SMSVerificationResponse> => {
  try {
    // Validate phone number format
    if (!phoneNumber || !/^\+?[1-9]\d{1,14}$/.test(phoneNumber.replace(/\D/g, ""))) {
      return {
        success: false,
        message: "Invalid phone number format",
      };
    }

    // Use Twilio Verify API for OTP
    const verification = await twilioClient.verify.v2
      .services(process.env.TWILIO_VERIFY_SERVICE_SID || "")
      .verifications.create({
        to: phoneNumber,
        channel: "sms",
      });

    return {
      success: true,
      message: "Verification code sent to your phone",
      verificationSid: verification.sid,
    };
  } catch (error) {
    console.error("[SMS] Failed to send verification:", error);
    return {
      success: false,
      message: "Failed to send verification code. Please try again.",
    };
  }
};

/**
 * Verify OTP code
 */
export const verifyOTP = async (
  phoneNumber: string,
  otp: string
): Promise<VerifyOTPResponse> => {
  try {
    // Validate OTP format (6 digits)
    if (!otp || !/^\d{6}$/.test(otp)) {
      return {
        success: false,
        message: "Invalid verification code format",
        verified: false,
      };
    }

    // Use Twilio Verify API to check OTP
    const verificationCheck = await twilioClient.verify.v2
      .services(process.env.TWILIO_VERIFY_SERVICE_SID || "")
      .verificationChecks.create({
        to: phoneNumber,
        code: otp,
      });

    if (verificationCheck.status === "approved") {
      return {
        success: true,
        message: "Phone number verified successfully",
        verified: true,
      };
    } else {
      return {
        success: false,
        message: "Invalid verification code",
        verified: false,
      };
    }
  } catch (error) {
    console.error("[SMS] Failed to verify OTP:", error);
    return {
      success: false,
      message: "Failed to verify code. Please try again.",
      verified: false,
    };
  }
};

/**
 * Update user's verified phone number
 */
export const updateVerifiedPhoneNumber = async (
  userId: number,
  phoneNumber: string
): Promise<boolean> => {
  try {
    // Phone verification not yet implemented in schema
    // Will be added when database is migrated
    return true;
  } catch (error) {
    console.error("[SMS] Failed to update phone number:", error);
    return false;
  }
};

/**
 * Get user's verified phone number
 */
export const getUserPhoneNumber = async (userId: number): Promise<string | null> => {
  try {
    // Phone number not yet implemented in schema
    // Return null for now - will be added when database is migrated
    return null;
  } catch (error) {
    console.error("[SMS] Failed to get phone number:", error);
    return null;
  }
};

/**
 * Check if phone number is verified
 */
export const isPhoneNumberVerified = async (userId: number): Promise<boolean> => {
  try {
    // Phone verification not yet implemented in schema
    // Return false for now - will be added when database is migrated
    return false;
  } catch (error) {
    console.error("[SMS] Failed to check phone verification:", error);
    return false;
  }
};

/**
 * Send SMS notification (for tournaments, bonuses, etc)
 */
export const sendSMSNotification = async (
  phoneNumber: string,
  message: string
): Promise<boolean> => {
  try {
    if (!process.env.TWILIO_PHONE_NUMBER) {
      console.warn("[SMS] TWILIO_PHONE_NUMBER not configured");
      return false;
    }

    await twilioClient.messages.create({
      body: message,
      from: process.env.TWILIO_PHONE_NUMBER,
      to: phoneNumber,
    });

    return true;
  } catch (error) {
    console.error("[SMS] Failed to send notification:", error);
    return false;
  }
};

/**
 * Send bulk SMS notifications
 */
export const sendBulkSMSNotifications = async (
  phoneNumbers: string[],
  message: string
): Promise<{ sent: number; failed: number }> => {
  let sent = 0;
  let failed = 0;

  for (const phoneNumber of phoneNumbers) {
    const success = await sendSMSNotification(phoneNumber, message);
    if (success) {
      sent++;
    } else {
      failed++;
    }
  }

  return { sent, failed };
};
