import { authApi } from "@/lib/api/api-service";
import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";




function randomToken() {
  return Math.random().toString(36).substring(2) + Date.now().toString(36);
}

const isMockMode = process.env.NEXT_PUBLIC_ENABLE_MOCK_MODE === "true";

const handler = NextAuth({
  providers: [
    Credentials({
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "text" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials) {
        console.log("credentials", credentials);
        if (!credentials?.email || !credentials?.password) {
          throw new Error("Email ve şifre gereklidir.");
        }

        // Eğer mock mod aktifse backend'e gitme
        if (isMockMode) {
          return {
            id: credentials.email,
            name: credentials.email.split("@")[0],
            email: credentials.email,
            accessToken: randomToken(),
            refreshToken: randomToken(),
          };
        }

        // Normal mod: backend'e istek at
        const res = await authApi.login({
          email: credentials.email,
          password: credentials.password,
        });

        // Axios interceptor otomatik unwrap yapıyor:
        // Backend { success, data: { accessToken, refreshToken, user } } sarıyor
        // Interceptor sonrası res = { accessToken, refreshToken, user }
        if (!res?.accessToken) {
          throw new Error("Giriş başarısız");
        }

        const { accessToken, refreshToken, user } = res;

        return {
          id: user.id,
          name: user.firstName
            ? `${user.firstName} ${user.lastName || ""}`.trim()
            : user.email.split("@")[0],
          email: user.email,
          accessToken,
          refreshToken,
          roles: user.roles || [],
        };
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user }: any) {
      if (user) {
        token.accessToken = user.accessToken;
        token.refreshToken = user.refreshToken;
        token.id = user.id;
        token.roles = user.roles;
      }
      return token;
    },
    async session({ session, token }: any) {
      session.user.id = token.id;
      session.user.roles = token.roles;
      session.accessToken = token.accessToken;
      session.refreshToken = token.refreshToken;
      return session;
    },
  },
  pages: {
    signIn: "/signin",
    error: "/signin",
  },
  session: { strategy: "jwt" },
  secret: process.env.NEXTAUTH_SECRET,
});

export { handler as GET, handler as POST };
