import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';

const BACKEND_URL = process.env.NEXT_PUBLIC_API_URL_INTERNAL ?? 'http://recipe-api:8080';

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Credentials({
      credentials: {
        username: { label: 'Användarnamn', type: 'text' },
        password: { label: 'Lösenord', type: 'password' },
      },
      async authorize(credentials) {
        if (!credentials?.username || !credentials?.password) return null;
        try {
          const res = await fetch(`${BACKEND_URL}/api/auth/login`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              username: credentials.username,
              password: credentials.password,
            }),
          });
          if (!res.ok) return null;
          const data = await res.json() as { accessToken: string; userId: number; username: string; role: string };
          return {
            id: String(data.userId),
            name: data.username,
            accessToken: data.accessToken,
            role: data.role,
          };
        } catch {
          return null;
        }
      },
    }),
  ],
  callbacks: {
    jwt({ token, user }) {
      if (user) {
        token.accessToken = (user as any).accessToken as string;
        token.userId = Number(user.id);
        token.username = user.name ?? '';
        token.role = (user as any).role as string;
        // eslint-disable-next-line no-console
        console.log('[NextAuth JWT callback] Token set:', {
          hasAccessToken: !!token.accessToken,
          role: token.role,
          username: token.username,
        });
      }
      return token;
    },
    session({ session, token }) {
      // eslint-disable-next-line no-console
      console.log('[NextAuth session callback] Token data:', {
        tokenAccessToken: token.accessToken,
        tokenRole: token.role,
        tokenUserId: token.userId,
      });
      if (token.accessToken) {
        session.accessToken = token.accessToken as string;
      } else {
        // eslint-disable-next-line no-console
        console.warn('[NextAuth session callback] WARNING: No accessToken in token!');
      }
      session.user.id = String(token.userId);
      session.user.name = token.username as string;
      (session.user as any).role = token.role as string;
      return session;
    },
  },
  pages: {
    signIn: '/login',
  },
  session: { strategy: 'jwt' },
});
