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.NODE_ENV !== "production" &&
  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 {
          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(),
              subscriptionPlan: "free",
            };
          }

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

          const response = res;

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

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

          // Extract subscription plan from user data (backend includes subscriptionStatus)
          const subscriptionPlan = (user as Record<string, unknown>)
            .subscriptionPlan as "free" | "plus" | "premium" | undefined;

          return {
            id: user.id,
            name: user.firstName
              ? `${user.firstName} ${user.lastName || ""}`.trim()
              : user.email.split("@")[0],
            email: user.email,
            accessToken,
            refreshToken,
            roles: normalizedRoles,
            subscriptionPlan: subscriptionPlan ?? "free",
          };
        } catch (error: unknown) {
          const err = error as Error & {
            response?: { data: unknown; status: number };
          };
          if (err.response) {
            // keep error logging for actual errors but remove verbose debugging
          }
          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);
        token.subscriptionPlan = user.subscriptionPlan ?? "free";
      }
      return token;
    },
    async session({ session, token }: { session: Session; token: JWT }) {
      session.user.id = token.id;
      session.user.roles = normalizeRoles(token.roles);
      session.user.subscriptionPlan = token.subscriptionPlan ?? "free";
      session.accessToken = token.accessToken;
      session.refreshToken = token.refreshToken;
      return session;
    },
  },
  session: { strategy: "jwt" },
  secret: process.env.NEXTAUTH_SECRET,
};
