import { cacheLife, cacheTag } from "next/cache"
import { checkAndResetSubscriptionPeriod, prisma } from "@codeflash-ai/common"

async function getUserDashboardData(user_id: string) {
  const [user, subscription] = await Promise.all([
    prisma.users.findUnique({
      where: { user_id },
      select: { onboarding_completed: true, privacy_mode: true },
    }),
    prisma.subscriptions.findUnique({
      where: { user_id },
      select: {
        plan_type: true,
        subscription_status: true,
        optimizations_used: true,
        optimizations_limit: true,
        current_period_start: true,
        current_period_end: true,
      },
    }),
  ])
  const isPaid =
    subscription &&
    subscription.subscription_status === "active" &&
    subscription.plan_type.toUpperCase() !== "FREE"
  return {
    onboarding_completed: user?.onboarding_completed ?? false,
    privacy_mode: user?.privacy_mode ?? false,
    can_use_privacy_mode: !!isPaid,
    subscription: subscription
      ? {
          optimizations_used: subscription.optimizations_used,
          optimizations_limit: subscription.optimizations_limit,
          plan_type: subscription.plan_type,
          subscription_status: subscription.subscription_status,
          current_period_start: subscription.current_period_start,
          current_period_end: subscription.current_period_end,
        }
      : null,
  }
}

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

export interface CachedDashboardData {
  onboardingCompleted: boolean
  organizations: Organization[]
  privacyMode: boolean
  canUsePrivacyMode: boolean
  subscription: {
    optimizations_used: number
    optimizations_limit: number
  } | null
}

/**
 * Fetches all dashboard layout data in one shot, cached across requests
 * using the "frequent" cacheLife profile (stale: 30s, revalidate: 60s).
 * userId is automatically part of the cache key (function argument).
 *
 * Invalidate with: updateTag(`dashboard:${userId}`)
 */
export async function getCachedDashboardData(userId: string): Promise<CachedDashboardData> {
  "use cache"
  cacheLife("frequent")
  cacheTag(`dashboard:${userId}`)

  // Consolidate user data queries: 4 separate queries → 2 parallel queries
  // (getUserDashboardData replaces hasCompletedOnboarding, getUserPrivacyMode, isUserPaid, subscription)
  const [userData, orgsResult] = await Promise.all([
    getUserDashboardData(userId).catch(() => ({
      onboarding_completed: false,
      privacy_mode: false,
      can_use_privacy_mode: false,
      subscription: null,
    })),

    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" },
      })
      .then(
        (
          orgs: Array<{ id: string; name: string; organization_members: Array<{ role: string }> }>,
        ) =>
          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`,
            }),
          ),
      )
      .catch(() => [] as Organization[]),
  ])

  // Check if subscription needs period reset (writes if necessary)
  let subscription: { optimizations_used: number; optimizations_limit: number } | null = null
  if (userData.subscription) {
    if (userData.subscription.plan_type === "FREE") {
      try {
        const resetSub = await checkAndResetSubscriptionPeriod(userId)
        if (resetSub) {
          subscription = {
            optimizations_used: resetSub.optimizations_used,
            optimizations_limit: resetSub.optimizations_limit,
          }
        }
      } catch {
        // Keep existing subscription data on error
        subscription = {
          optimizations_used: userData.subscription.optimizations_used,
          optimizations_limit: userData.subscription.optimizations_limit,
        }
      }
    } else {
      // For non-free plans, just extract the fields we need
      subscription = {
        optimizations_used: userData.subscription.optimizations_used,
        optimizations_limit: userData.subscription.optimizations_limit,
      }
    }
  }

  return {
    onboardingCompleted: userData.onboarding_completed,
    organizations: orgsResult,
    privacyMode: userData.privacy_mode,
    canUsePrivacyMode: userData.can_use_privacy_mode,
    subscription,
  }
}
