"use server"

import { revalidatePath } from "next/cache"
import { getSessionUser } from "@/lib/session"
import { getAccountContext } from "@/lib/account"
import { disconnect, syncNow, getProvider, type Provider } from "@/lib/accounting"

async function ownerGuard() {
  const user = await getSessionUser()
  if (!user) throw new Error("Unauthorized")
  const ctx = await getAccountContext(user.id)
  if (!ctx.isOwner) throw new Error("Only the account owner can manage integrations")
  return ctx
}

export async function disconnectAccounting(provider: string) {
  const ctx = await ownerGuard()
  if (!getProvider(provider)) throw new Error("Unknown provider")
  await disconnect(ctx.ownerId, provider as Provider)
  revalidatePath("/settings/integrations")
  return { ok: true }
}

export async function syncAccountingNow(provider: string) {
  const ctx = await ownerGuard()
  if (!getProvider(provider)) throw new Error("Unknown provider")
  const result = await syncNow(ctx.ownerId, provider as Provider)
  revalidatePath("/settings/integrations")
  return { ok: true, ...result }
}
