"use server";

import { cookies } from "next/headers";
import { getSession } from "@/lib/auth";

export type WholesaleLoginResult =
  | { success: true; token: string; userId: string; customerId: string }
  | { success: false; error: string };

export type EmployeeSession = {
  userId: string;
  brandId: string;
  name: string;
  email?: string;
  brandName: string;
};

const NOT_AVAILABLE_ERROR =
  "Wholesale customer login is temporarily unavailable while we rebuild authentication. Please contact your account manager.";

export async function wholesaleLoginAction(_formData: FormData): Promise<WholesaleLoginResult> {
  await getSession();
  return { success: false, error: NOT_AVAILABLE_ERROR };
}

export async function wholesaleLogoutAction(): Promise<{ success: true } | { success: false; error: string }> {
  await getSession();
  const cookieStore = await cookies();
  // Best-effort cookie cleanup so a returning customer doesn't see stale state
  cookieStore.delete("wholesale_session");
  return { success: true };
}

export async function wholesaleEmployeeLogoutAction(): Promise<{ success: true } | { success: false; error: string }> {
  await getSession();
  const cookieStore = await cookies();
  // Best-effort cookie cleanup so a returning employee doesn't see stale state
  cookieStore.delete("employee_session");
  return { success: true };
}

export async function getEmployeeSessionAction(): Promise<EmployeeSession | null> {
  await getSession();
  const cookieStore = await cookies();
  const sessionCookie = cookieStore.get("employee_session")?.value;
  if (!sessionCookie) return null;

  try {
    const parsed = JSON.parse(sessionCookie) as {
      user_id?: string;
      brand_id?: string;
      name?: string;
      email?: string;
      brand_name?: string;
    };
    if (!parsed.user_id || !parsed.brand_id) return null;
    return {
      userId: parsed.user_id,
      brandId: parsed.brand_id,
      name: parsed.name || parsed.email || "Employee",
      email: parsed.email,
      brandName: parsed.brand_name || "Pickup Portal",
    };
  } catch {
    return null;
  }
}