import { authService } from "@/lib/api/auth/service";
import { normalizeRoles } from "@/lib/auth/roles";
import type { NextAuthOptions } from "next-auth";
import type { JWT } from "next-auth/jwt";
import type { Session, User } 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";

export const authOptions: NextAuthOptions = {
  providers: [
    Credentials({
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "text" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials) {
        try {
          console.log("Starting authorization with:", {
            email: credentials?.email,
          });

          if (!credentials?.email || !credentials?.password) {
            throw new Error("Email ve şifre gereklidir.");
          }

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

          // Normal mod: backend'e istek at
          console.log("Sending login request to backend...");
          const res = await authService.login({
            email: credentials.email,
            password: credentials.password,
          });

          console.log(
            "Backend response received:",
            JSON.stringify(res, null, 2),
          );

          const response = res;

          // Backend returns ApiResponse<TokenResponseDto>
          // Structure: { data: { accessToken, refreshToken, expiresIn, user }, message, statusCode }
          if (!res.success || !response?.data?.accessToken) {
            console.error("Login failed or no access token in response");
            throw new Error(response?.message || "Giriş başarısız");
          }

          const { accessToken, refreshToken, user } = response.data;
          const normalizedRoles = normalizeRoles(user.roles);

          console.log("Login successful, creating user session object");

          return {
            id: user.id,
            name: user.firstName
              ? `${user.firstName} ${user.lastName || ""}`.trim()
              : user.email.split("@")[0],
            email: user.email,
            accessToken,
            refreshToken,
            roles: normalizedRoles,
          };
        } catch (error: unknown) {
          console.error("Authorize error detailed:", error);
          const err = error as Error & {
            response?: { data: unknown; status: number };
          };
          if (err.response) {
            console.error("Error response data:", err.response.data);
            console.error("Error response status:", err.response.status);
          }
          throw new Error(
            err.message || "An error occurred during authentication",
          );
        }
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user }: { token: JWT; user?: User }) {
      if (user) {
        token.accessToken = user.accessToken;
        token.refreshToken = user.refreshToken;
        token.id = user.id;
        token.roles = normalizeRoles(user.roles);
      }
      return token;
    },
    async session({ session, token }: { session: Session; token: JWT }) {
      session.user.id = token.id;
      session.user.roles = normalizeRoles(token.roles);
      session.accessToken = token.accessToken;
      session.refreshToken = token.refreshToken;
      return session;
    },
  },
  session: { strategy: "jwt" },
  secret: process.env.NEXTAUTH_SECRET,
};
