import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/lib/prisma";
import bcrypt from "bcryptjs";
import { ZodError } from "zod";
import { loginSchema } from "./features/auth/schemas";
import AuthentikProvider from "next-auth/providers/authentik";

console.log('🔥 AUTH: Auth configuration loading...')

export const { handlers, signIn, signOut, auth } = NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    {
      id: "authentik",
      name: "Authentik",
      type: "oidc",
      clientId: process.env.AUTHENTIK_ID,
      clientSecret: process.env.AUTHENTIK_SECRET,
      issuer: "https://authentik.lci.ge/application/o/jira/",
      checks: ["pkce", "state"],
      profile(profile) {
        console.log('🔥 AUTH: Authentik profile received:', profile)
        return {
          id: profile.sub,
          name: profile.name || profile.preferred_username,
          email: profile.email,
          image: profile.picture,
        };
      },
    },
    Credentials({
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Password", type: "password" },
      },
      authorize: async (credentials) => {
        console.log('🔥 AUTH: Credentials authorize called')
        try {
          if (!credentials?.email || !credentials?.password) {
            console.log('🔥 AUTH: Missing credentials')
            return null;
          }

          const { email, password } = await loginSchema.parseAsync(credentials);
          console.log('🔥 AUTH: Looking up user:', email)

          const user = await prisma.user.findUnique({
            where: {
              email: email,
            },
          });

          if (!user || !user.hashedPassword) {
            console.log("🔥 AUTH: User not found or no password");
            return null;
          }

          const passwordsMatch = await bcrypt.compare(
            password,
            user.hashedPassword
          );

          if (!passwordsMatch) {
            console.log("🔥 AUTH: Passwords don't match");
            return null;
          }

          console.log("🔥 AUTH: User authenticated successfully:", user.id);
          return {
            id: user.id,
            email: user.email,
            name: user.name
          };
        } catch (error) {
          console.error("🔥 AUTH ERROR:", error);
          return null;
        }
      },
    }),
  ],
  session: { strategy: "jwt" },
  pages: { signIn: "/sign-in" },
  debug: process.env.NODE_ENV === "development",
  secret: process.env.AUTH_SECRET || "your-fallback-secret-for-development",
  callbacks: {
    session: ({ session, token }) => {
      console.log('🔥 AUTH: Session callback called')
      return {
        ...session,
        user: {
          ...session.user,
          id: token.id,
        },
      }
    },
    jwt: ({ token, user }) => {
      console.log('🔥 AUTH: JWT callback called')
      if (user) {
        token.id = user.id;
      }
      return token;
    },
  },
});

console.log('🔥 AUTH: Auth configuration completed')

export const authOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [Credentials],
  session: { strategy: "jwt" },
};