import { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { api } from "@/lib/api";

export const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      name: "credentials",
      credentials: {
        email: { label: "邮箱", type: "email" },
        password: { label: "密码", type: "password" },
      },
      async authorize(credentials) {
        console.log("[NextAuth] authorize called with email:", credentials?.email);
        if (!credentials?.email || !credentials?.password) {
          console.log("[NextAuth] missing credentials");
          return null;
        }
        try {
          const res = await api.auth.login({
            email: credentials.email,
            password: credentials.password,
          });
          console.log("[NextAuth] login response:", JSON.stringify({
            hasAccessToken: !!res.access_token,
            userId: res.user?.id,
            userEmail: res.user?.email,
            isAdmin: res.user?.is_admin,
          }));
          if (res.access_token) {
            const user = {
              id: res.user?.id || credentials.email,
              name: res.user?.name,
              email: res.user?.email,
              accessToken: res.access_token,
              is_admin: res.user?.is_admin || false,
            };
            console.log("[NextAuth] returning user:", JSON.stringify(user));
            return user;
          }
          console.log("[NextAuth] no access_token in response");
          return null;
        } catch (error) {
          console.error("[NextAuth] authorize error:", error);
          return null;
        }
      },
    }),
  ],
  session: {
    strategy: "jwt",
  },
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.accessToken = user.accessToken;
        token.id = user.id;
        token.is_admin = user.is_admin;
      }
      return token;
    },
    async session({ session, token }) {
      session.accessToken = token.accessToken as string;
      session.user.id = token.id as string;
      session.user.is_admin = token.is_admin as boolean;
      return session;
    },
  },
  pages: {
    signIn: "/login",
  },
};
