import { env } from "cloudflare:workers";
import { getChatGPTUser } from "./chatgpt-auth";

export type AppRole = "learner" | "creator" | "admin";

export async function getAppIdentity() {
  const user = await getChatGPTUser();
  if (!user) return null;
  try {
    const owner = await env.DB.prepare(
      "SELECT value FROM platform_settings WHERE key='owner_email'"
    ).first<{ value: string }>();
    if (owner?.value.toLowerCase() === user.email.toLowerCase()) {
      return { ...user, role: "admin" as AppRole };
    }
    const member = await env.DB.prepare(
      "SELECT role, status FROM organisation_members WHERE lower(email)=lower(?)"
    ).bind(user.email).first<{ role: AppRole; status: "invited" | "active" | "suspended" }>();
    if (member?.status === "suspended") return null;
    if (member) return { ...user, role: member.role };
  } catch {
    // Membership migrations may not have run on an older local database yet.
  }
  const row = await env.DB.prepare("SELECT active_role AS activeRole FROM learner_state WHERE email=?")
    .bind(user.email).first<{ activeRole: AppRole | null }>();
  return { ...user, role: (row?.activeRole ?? "learner") as AppRole };
}

export function unauthorised() {
  return Response.json({ error: "Sign in is required." }, { status: 401 });
}

export function forbidden() {
  return Response.json({ error: "Your account does not have permission for this action." }, { status: 403 });
}
