import { NextResponse } from "next/server"
import { and, eq } from "drizzle-orm"
import { z } from "zod"
import { db } from "@/lib/db"
import { account_members } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"

const patchSchema = z.object({
  role: z.enum(["member", "viewer"]),
})

/**
 * PATCH — change a member's role (member <-> viewer). Owner-only; scoped to
 * rows the session user owns so a member can't edit someone else's team.
 */
export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const user = await getSessionUser()
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

  const { id } = await params
  const body = await request.json().catch(() => null)
  const parsed = patchSchema.safeParse(body)
  if (!parsed.success) {
    return NextResponse.json(
      { error: parsed.error.issues[0]?.message ?? "Invalid input" },
      { status: 400 }
    )
  }

  const [updated] = await db
    .update(account_members)
    .set({ role: parsed.data.role })
    .where(and(eq(account_members.id, id), eq(account_members.owner_id, user.id)))
    .returning({
      id: account_members.id,
      email: account_members.email,
      role: account_members.role,
      status: account_members.status,
    })

  if (!updated) return NextResponse.json({ error: "Not found" }, { status: 404 })

  return NextResponse.json(updated)
}

/**
 * DELETE — revoke a member's access. Sets status='revoked' and clears
 * member_id so getAccountContext immediately stops resolving them to this
 * owner. Owner-only; scoped to rows the session user owns.
 */
export async function DELETE(_: Request, { params }: { params: Promise<{ id: string }> }) {
  const user = await getSessionUser()
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

  const { id } = await params

  const [revoked] = await db
    .update(account_members)
    .set({ status: "revoked", member_id: null })
    .where(and(eq(account_members.id, id), eq(account_members.owner_id, user.id)))
    .returning({ id: account_members.id })

  if (!revoked) return NextResponse.json({ error: "Not found" }, { status: 404 })

  return NextResponse.json({ ok: true })
}
