import NextAuth from "next-auth";
import { PrismaAdapter } from "@auth/prisma-adapter";
import CredentialsProvider from "next-auth/providers/credentials";
import GoogleProvider from "next-auth/providers/google";
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/prisma";
import { loginSchema } from "@/lib/validations/auth";

export const { handlers, signIn, signOut, auth } = NextAuth({
  adapter: PrismaAdapter(prisma) as any,
  session: { strategy: "jwt" },
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
    CredentialsProvider({
      name: "credentials",
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Mot de passe", type: "password" },
      },
      async authorize(credentials) {
        const parsed = loginSchema.safeParse(credentials);
        if (!parsed.success) return null;

        const user = await prisma.user.findUnique({
          where: { email: parsed.data.email },
        });
        if (!user || !user.password) return null;

        const isValid = await bcrypt.compare(parsed.data.password, user.password);
        if (!isValid) return null;

        await prisma.user.update({
          where: { id: user.id },
          data: { lastLoginAt: new Date() },
        });

        return user;
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.id = user.id;
        token.isSuperAdmin = (user as any).isSuperAdmin;
        // Stocker l'orgId dans le token pour éviter une requête Prisma à chaque appel API
        const membership = await prisma.organizationMember.findFirst({
          where: { userId: user.id as string, joinedAt: { not: null } },
          select: { organizationId: true },
          orderBy: { createdAt: "asc" },
        });
        token.organizationId = membership?.organizationId ?? null;
      }
      return token;
    },
    async session({ session, token }) {
      if (token.id) {
        session.user.id = token.id as string;
        (session.user as any).isSuperAdmin = token.isSuperAdmin;
        (session.user as any).organizationId = token.organizationId;
      }
      return session;
    },
    async signIn({ user, account }) {
      // Autoriser OAuth sans vérification d'email
      if (account?.provider !== "credentials") return true;
      if (!(user as any).emailVerified && account?.provider === "credentials") {
        // En production, bloquer les emails non vérifiés
        // return false;
      }
      return true;
    },
  },
  pages: {
    signIn: "/connexion",
    error: "/connexion",
    newUser: "/onboarding",
  },
  events: {
    async createUser({ user }) {
      // Envoi email de bienvenue (optionnel)
      console.log("Nouvel utilisateur:", user.email);
    },
  },
});

// ─── Helpers côté serveur ─────────────────────────────────────

export async function getCurrentUser() {
  const session = await auth();
  return session?.user ?? null;
}

export async function requireAuth() {
  const user = await getCurrentUser();
  if (!user) throw new Error("Non authentifié");
  return user;
}

/**
 * Retourne { userId, orgId } depuis la session JWT — SANS requête Prisma.
 * Fallback Prisma si l'orgId n'est pas encore dans le token (ancienne session).
 */
export async function getSessionContext() {
  const session = await auth();
  if (!session?.user?.id) return null;

  const userId = session.user.id;
  let orgId = (session.user as any).organizationId as string | null | undefined;

  // Fallback pour les sessions créées avant la migration du token
  if (!orgId) {
    const m = await prisma.organizationMember.findFirst({
      where: { userId, joinedAt: { not: null } },
      select: { organizationId: true },
      orderBy: { createdAt: "asc" },
    });
    orgId = m?.organizationId ?? null;
  }

  return orgId ? { userId, orgId } : null;
}

export async function getOrganizationMembership(userId: string, organizationId: string) {
  return prisma.organizationMember.findUnique({
    where: { organizationId_userId: { organizationId, userId } },
    include: { organization: true },
  });
}

export async function requireOrgAccess(userId: string, organizationId: string, minRole?: string) {
  const membership = await getOrganizationMembership(userId, organizationId);
  if (!membership) throw new Error("Accès refusé");
  return membership;
}
