/**
 * SMS Sender — Twilio via fetch (no SDK). Dev stub when not configured.
 */

import { prisma } from "@/lib/prisma";
import { randomInt } from "crypto";

const SID = process.env.TWILIO_ACCOUNT_SID ?? "";
const TOKEN = process.env.TWILIO_AUTH_TOKEN ?? "";
const FROM = process.env.TWILIO_PHONE_NUMBER ?? "";

export interface SmsResult { success: boolean; error?: string }

export async function sendSms(to: string, message: string): Promise<SmsResult> {
  // Truncate to 160 chars for single SMS
  const body = message.length > 157 ? message.slice(0, 157) + "..." : message;

  if (!SID || !TOKEN || !FROM) {
    console.log(`[SMS stub] To: ${to}, Message: ${body}`);
    return { success: true };
  }

  try {
    const res = await fetch(`https://api.twilio.com/2010-04-01/Accounts/${SID}/Messages.json`, {
      method: "POST",
      headers: {
        Authorization: `Basic ${Buffer.from(`${SID}:${TOKEN}`).toString("base64")}`,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: new URLSearchParams({ To: to, From: FROM, Body: body }).toString(),
    });
    if (!res.ok) {
      const err = await res.text().catch(() => "");
      return { success: false, error: `Twilio ${res.status}: ${err.slice(0, 200)}` };
    }
    return { success: true };
  } catch (err) {
    return { success: false, error: err instanceof Error ? err.message : "SMS failed" };
  }
}

// ─── Opt-in flow ────────────────────────────────────────────────────────────

export async function requestSmsOptIn(userId: string, phone: string): Promise<void> {
  const code = String(randomInt(100000, 999999));
  const codeExpiresAt = new Date(Date.now() + 10 * 60 * 1000);

  await prisma.smsOptIn.upsert({
    where: { userId },
    create: { userId, phone, verifyCode: code, codeExpiresAt },
    update: { phone, verifyCode: code, codeExpiresAt, isVerified: false, isActive: false },
  });

  await sendSms(phone, `Your meSEO verification code is: ${code}. Reply STOP to opt out.`);
}

export async function verifySmsOptIn(userId: string, code: string): Promise<boolean> {
  const record = await prisma.smsOptIn.findUnique({ where: { userId } });
  if (!record || record.verifyCode !== code) return false;
  if (record.codeExpiresAt && record.codeExpiresAt < new Date()) return false;

  await prisma.smsOptIn.update({
    where: { userId },
    data: { isVerified: true, isActive: true, optedInAt: new Date(), verifyCode: null, codeExpiresAt: null },
  });
  return true;
}

export async function optOutSms(userId: string): Promise<void> {
  await prisma.smsOptIn.update({ where: { userId }, data: { isActive: false, optedOutAt: new Date() } });
}

export async function getVerifiedPhone(userId: string): Promise<string | null> {
  const record = await prisma.smsOptIn.findUnique({ where: { userId } });
  return record?.isActive && record.isVerified ? record.phone : null;
}
