"use server"

import { prisma } from "@codeflash-ai/common"
import { dedup } from "@/lib/request-dedup"

interface Organization {
  id: string
  name: string
  role: "admin" | "owner" | "member"
  avatarUrl?: string
}

export async function getUserOrganizations(
  userId: string,
): Promise<{ success: boolean; organizations?: Organization[]; error?: string }> {
  return dedup(`orgs:${userId}`, async () => {
    try {
      const orgs = await prisma.organizations.findMany({
        where: {
          organization_members: {
            some: { user_id: userId },
          },
        },
        select: {
          id: true,
          name: true,
          organization_members: {
            where: { user_id: userId },
            select: { role: true },
          },
        },
        orderBy: { created_at: "desc" },
      })

      const organizations = orgs.map(
        (org: { id: string; name: string; organization_members: Array<{ role: string }> }) => ({
          id: org.id,
          name: org.name,
          role: org.organization_members[0].role as "admin" | "owner" | "member",
          avatarUrl: `https://github.com/${org.name}.png`,
        }),
      )

      return { success: true, organizations }
    } catch (error) {
      console.error("Failed to get user organizations:", error)
      return {
        success: false,
        error: error instanceof Error ? error.message : "Failed to get organizations",
      }
    }
  })
}
