"use server"

import { createId } from "@paralleldrive/cuid2"
import { db } from "@/shared/db"
import { loginLogs } from "@/shared/db/schema"
import { resolveClientIp, getUserAgent } from "@/shared/lib/http-utils"

export type LoginLogAction = "signin" | "signout" | "signup"
export type LoginLogStatus = "success" | "failure"

export interface LogLoginEventParams {
  userId?: string
  userEmail: string
  action: LoginLogAction
  status?: LoginLogStatus
  errorMessage?: string
}

/**
 * Record a login-related log entry (signin/signout/signup).
 * Does NOT depend on auth context since it runs during auth events.
 * Silently fails on error so it never breaks the auth flow.
 */
export async function logLoginEvent(params: LogLoginEventParams): Promise<void> {
  try {
    const ipAddress = await resolveClientIp()
    const userAgent = await getUserAgent()

    await db.insert(loginLogs).values({
      id: createId(),
      userId: params.userId ?? null,
      userEmail: params.userEmail,
      action: params.action,
      status: params.status ?? "success",
      ipAddress,
      userAgent,
      errorMessage: params.errorMessage ?? null,
    })
  } catch {
    // Silently fail - logging should not break the auth flow
  }
}
