import { Password } from "@convex-dev/auth/providers/Password";
import { convexAuth } from "@convex-dev/auth/server";
import { DataModel } from "./_generated/dataModel";
import type { DatabaseWriter } from "./_generated/server";

/**
 * Convex Auth with password sign-in. Accounts are created by an administrator
 * (no self-service sign-up); the `profile` maps the email onto the worker
 * record so an existing user document is reused on first login.
 */
export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({
  providers: [
    Password<DataModel>({
      profile(params) {
        return { email: String(params.email ?? "").toLowerCase().trim() };
      },
      validatePasswordRequirements(password: string) {
        if (password.length < 8) throw new Error("Password must be at least 8 characters.");
      },
    }),
  ],
  callbacks: {
    async createOrUpdateUser(ctx, args) {
      // Never auto-provision accounts from the login form: only administrators create workers.
      const db = ctx.db as unknown as DatabaseWriter;
      if (args.existingUserId) {
        const u = await db.get(args.existingUserId);
        if (u?.status && u.status !== "ACTIVE") throw new Error("This account is disabled. Contact an administrator.");
        if (u?.deletedAt) throw new Error("This account no longer exists.");
        return args.existingUserId;
      }
      const email = args.profile.email as string | undefined;
      const existing = email ? await db.query("users").withIndex("email", (q) => q.eq("email", email)).unique() : null;
      if (existing) return existing._id;
      throw new Error("No account with this email. Accounts are created by the administrator.");
    },
  },
});
