import { db } from '../db/db_index'
import { notifCreds, unloggedUserTokens, userCreds, userDetails, users } from '../db/schema'
import { and, eq } from 'drizzle-orm'

export async function getUserById(userId: number) {
  const [user] = await db.select().from(users).where(eq(users.id, userId)).limit(1)
  return user || null
}

export async function getUserDetailByUserId(userId: number) {
  const [detail] = await db.select().from(userDetails).where(eq(userDetails.userId, userId)).limit(1)
  return detail || null
}

export async function getUserWithCreds(userId: number) {
  const result = await db
    .select()
    .from(users)
    .leftJoin(userCreds, eq(users.id, userCreds.userId))
    .where(eq(users.id, userId))
    .limit(1)

  if (result.length === 0) return null
  return {
    user: result[0].users,
    creds: result[0].user_creds,
  }
}

export async function getNotifCred(userId: number, token: string) {
  return db.query.notifCreds.findFirst({
    where: and(eq(notifCreds.userId, userId), eq(notifCreds.token, token)),
  })
}

export async function upsertNotifCred(userId: number, token: string): Promise<void> {
  const existing = await getNotifCred(userId, token)
  if (existing) {
    await db.update(notifCreds)
      .set({ lastVerified: new Date() })
      .where(eq(notifCreds.id, existing.id))
    return
  }

  await db.insert(notifCreds).values({
    userId,
    token,
    lastVerified: new Date(),
  })
}

export async function deleteUnloggedToken(token: string): Promise<void> {
  await db.delete(unloggedUserTokens).where(eq(unloggedUserTokens.token, token))
}

export async function getUnloggedToken(token: string) {
  return db.query.unloggedUserTokens.findFirst({
    where: eq(unloggedUserTokens.token, token),
  })
}

export async function upsertUnloggedToken(token: string): Promise<void> {
  const existing = await getUnloggedToken(token)
  if (existing) {
    await db.update(unloggedUserTokens)
      .set({ lastVerified: new Date() })
      .where(eq(unloggedUserTokens.id, existing.id))
    return
  }

  await db.insert(unloggedUserTokens).values({
    token,
    lastVerified: new Date(),
  })
}
