import NextAuth from "next-auth";
import Google from "next-auth/providers/google";
import Facebook from "next-auth/providers/facebook";
import Credentials from "next-auth/providers/credentials";
import { authService } from "@/services/authService";

export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [
    Google({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
    Facebook({
      clientId: process.env.FACEBOOK_CLIENT_ID!,
      clientSecret: process.env.FACEBOOK_CLIENT_SECRET!,
    }),
    Credentials({
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials) {
        try {
          const response = await authService.login({
            email: credentials.email as string,
            password: credentials.password as string,
          });

          if (response.token && response.user) {
            return {
              id: response.user.id.toString(),
              email: response.user.email,
              name: response.user.name,
              token: response.token,
            };
          }
          return null;
        } catch (error) {
          console.error("Auth error:", error);
          return null;
        }
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user, account }) {
      // Initial sign in
      if (user) {
        token.id = user.id;
        token.email = user.email;
        token.name = user.name;
        
        // For OAuth providers
        if (account?.provider === "google" || account?.provider === "facebook") {
          token.provider = account.provider;
          token.accessToken = account.access_token;
          
          // Send OAuth token to backend
          try {
            const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/oauth/callback`, {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                provider: account.provider,
                access_token: account.access_token,
              }),
            });

            const data = await response.json();
            
            if (data.token) {
              token.backendToken = data.token;
              token.user = data.user;
            }
          } catch (error) {
            console.error("Backend OAuth error:", error);
          }
        } else if (account?.provider === "credentials") {
          // For credentials login
          token.backendToken = (user as { token?: string }).token;
        }
      }

      return token;
    },
    async session({ session, token }) {
      if (token) {
        session.user.id = token.id as string;
        session.user.email = token.email as string;
        session.user.name = token.name as string;
        (session as { backendToken?: string }).backendToken = token.backendToken as string;
        (session as { provider?: string }).provider = token.provider as string;
      }

      return session;
    },
  },
  pages: {
    signIn: "/login",
    error: "/login",
  },
  session: {
    strategy: "jwt",
  },
  secret: process.env.NEXTAUTH_SECRET,
});
