"use server"

import { prisma } from "@/lib/prisma"
import type { Member, UserRole } from "@/lib/types"
import { getActionAccountContext } from "@/lib/server/get-account-context"

/**
 * Server-side function to fetch all data needed for the members page in parallel.
 * Uses @/lib/prisma directly to avoid pulling in @codeflash-ai/common at build time.
 */
export async function getMembersPageInitData() {
  const accountContext = await getActionAccountContext()
  if (!accountContext) {
    return null
  }

  const { payload, userId } = accountContext
  const orgId = "orgId" in payload ? payload.orgId : null

  if (!orgId) {
    return { userId, orgId: null, members: [] as Member[], currentUserRole: null }
  }

  // Single query fetches org with all members (including current user's role)
  const org = await prisma.organizations.findUnique({
    where: { id: orgId },
    select: {
      id: true,
      organization_members: {
        include: {
          user: {
            select: { user_id: true, github_username: true, name: true, email: true },
          },
        },
        orderBy: { added_at: "asc" },
      },
    },
  })

  if (!org) {
    return { userId, orgId, members: [] as Member[], currentUserRole: null }
  }

  // Check access and extract current user's role from the same query result
  const currentUserMember = org.organization_members.find(
    (m: { user_id: string }) => m.user_id === userId,
  )
  if (!currentUserMember) {
    return { userId, orgId, members: [] as Member[], currentUserRole: null }
  }

  const members: Member[] = org.organization_members.map(
    (member: {
      id: string
      user_id: string
      role: string
      added_at: Date
      user: { user_id: string; github_username: string; name: string | null; email: string | null }
    }) => ({
      id: member.id,
      user_id: member.user_id,
      username: member.user.github_username,
      name: member.user.name,
      email: member.user.email,
      role: member.role,
      added_at: member.added_at,
      avatarUrl: `https://github.com/${member.user.github_username}.png`,
    }),
  )

  return {
    userId,
    orgId,
    members,
    currentUserRole: (currentUserMember.role as UserRole) ?? null,
  }
}
