"use server";

/** Server Actions ورود و خروج */
import { env } from "@/lib/env";
import { mobileSchema, otpSchema } from "@/validation/common";
import { requestOtp, verifyOtp, OTP_TTL_SECONDS } from "@/server/auth/otp";
import { createSession, destroySession } from "@/server/auth/session";
import { mergeGuestCart } from "@/server/services/cart-store";
import { isPrelaunch, PRELAUNCH_MESSAGE } from "@/lib/prelaunch";

export type AuthActionResult = { ok: true; phone?: string; ttl?: number; devCode?: string } | { ok: false; error: string; retryAfter?: number };

export async function requestOtpAction(rawPhone: string): Promise<AuthActionResult> {
  if (isPrelaunch()) return { ok: false, error: PRELAUNCH_MESSAGE };
  const phone = mobileSchema.safeParse(rawPhone);
  if (!phone.success) return { ok: false, error: phone.error.issues[0].message };
  const res = await requestOtp(phone.data);
  if (!res.ok) return res;
  const e = env();
  // فقط در توسعه با سرویس console، کد برای راحتی تست به فرم برگردانده می‌شود
  const devCode = e.NODE_ENV !== "production" && e.SMS_PROVIDER === "console" ? res.code : undefined;
  return { ok: true, phone: phone.data, ttl: OTP_TTL_SECONDS, devCode };
}

export async function verifyOtpAction(rawPhone: string, rawCode: string): Promise<AuthActionResult> {
  const phone = mobileSchema.safeParse(rawPhone);
  const code = otpSchema.safeParse(rawCode);
  if (!phone.success) return { ok: false, error: phone.error.issues[0].message };
  if (!code.success) return { ok: false, error: code.error.issues[0].message };
  const res = await verifyOtp(phone.data, code.data);
  if (!res.ok) return res;
  await mergeGuestCart(res.userId);
  await createSession(res.userId);
  return { ok: true };
}

export async function signOutAction() {
  await destroySession();
}
