import { db } from "@/lib/db";
import { botSessions } from "@/lib/schema";
import { eq } from "drizzle-orm";

export type BotState =
  | "idle"
  | "awaiting_payment_type"
  | "awaiting_service_select"
  | "awaiting_service_mode"
  | "awaiting_specific_service_select"
  | "awaiting_confirm";

export interface OcrData {
  amount?: number;
  date?: string;
  reference?: string;
  bank?: string;
  rawText?: string;
}

export interface BotContext {
  ocrData?: OcrData;
  selectedPaymentType?: "alquiler" | "servicio";
  selectedServicePaymentMode?: "global" | "specific";
  selectedServiceId?: number;
  selectedServiceName?: string;
  imageUrl?: string | null;
  senderName?: string;
}

export async function getSession(phone: string): Promise<{ state: BotState; context: BotContext }> {
  const rows = await db.select().from(botSessions).where(eq(botSessions.phone, phone));
  if (rows.length === 0) return { state: "idle", context: {} };
  return {
    state: (rows[0].state as BotState) ?? "idle",
    context: (rows[0].context as BotContext) ?? {},
  };
}

export async function setSession(phone: string, state: BotState, context: BotContext): Promise<void> {
  await db
    .insert(botSessions)
    .values({ phone, state, context })
    .onConflictDoUpdate({
      target: botSessions.phone,
      set: { state, context },
    });
}

export async function clearSession(phone: string): Promise<void> {
  await setSession(phone, "idle", {});
}
