import type {
  Feedback,
  InsertFeedback,
  InsertSubscriber
} from '@@/types/database'
import { useDB, eq, desc } from '../../utils/database'
import * as tables from '../schema'
import { getSuperAdminUsers } from './users'
import { sendNotification } from '../../utils/notifications'

export const createFeedback = async (payload: InsertFeedback) => {
  const db = useDB()

  // Create the feedback
  const [feedback] = await db
    .insert(tables.feedback)
    .values(payload)
    .returning()

  // Get the user who created the feedback
  const [feedbackUser] = await db
    .select({
      id: tables.user.id,
      name: tables.user.name,
      email: tables.user.email,
      image: tables.user.image
    })
    .from(tables.user)
    .where(eq(tables.user.id, payload.userId))
    .limit(1)

  if (feedbackUser) {
    // Get all super admin users
    const superAdmins = await getSuperAdminUsers()

    // Create notifications for each super admin
    await Promise.all(
      superAdmins.map(async (admin) => {
        await sendNotification({
          userId: admin.id,
          senderName: feedbackUser.name,
          senderEmail: feedbackUser.email,
          senderAvatar: feedbackUser.image ?? undefined,
          body: 'submitted new feedback',
          url: '/dashboard/admin/support-requests'
        })
      })
    )
  }

  return feedback
}

export const getAllFeedback = async () => {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const db = useDB() as any
  const feedbackRecords = await db.query.feedback.findMany({
    with: {
      user: {
        columns: {
          id: true,
          name: true,
          email: true,
          image: true
        }
      }
    },
    orderBy: [desc(tables.feedback.createdAt)]
  })
  return feedbackRecords
}

export const updateFeedback = async (
  id: string,
  payload: Partial<Feedback>
) => {
  const [feedback] = await useDB()
    .update(tables.feedback)
    .set(payload)
    .where(eq(tables.feedback.id, id))
    .returning()
  return feedback
}

export const deleteFeedback = async (id: string) => {
  const feedback = await useDB()
    .delete(tables.feedback)
    .where(eq(tables.feedback.id, id))
  return feedback
}

export const getFeedbackById = async (id: string) => {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const db = useDB() as any
  const feedback = await db.query.feedback.findFirst({
    where: eq(tables.feedback.id, id),
    with: {
      user: {
        columns: {
          id: true,
          name: true,
          email: true,
          image: true
        }
      }
    }
  })
  return feedback
}

export const getFeedbackByUserId = async (userId: string) => {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const db = useDB() as any
  const feedback = await db.query.feedback.findMany({
    where: eq(tables.feedback.userId, userId)
  })
  return feedback
}

export const insertSubscriber = async (payload: InsertSubscriber) => {
  const [subscriber] = await useDB()
    .insert(tables.subscribers)
    .values(payload)
    .returning()
  return subscriber
}

export const getAllSubscribers = async () => {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const db = useDB() as any
  const subscribers = await db.query.subscribers.findMany()
  return subscribers
}
