// /opt/erp-system/app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import prisma from "../../../../lib/prisma";
import bcrypt from "bcryptjs";

export const authOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Passwort", type: "password" }
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) return null;
        
        const teamUser = await prisma.user.findUnique({
          where: { email: credentials.email },
          include: { role: true } 
        });
        
        if (teamUser) {
          const match = await bcrypt.compare(credentials.password, teamUser.passwordHash);
          if (match) {
            return {
              id: `TEAM_${teamUser.id}`, dbId: teamUser.id, email: teamUser.email,
              firstName: teamUser.firstName, lastName: teamUser.lastName,
              roleName: teamUser.role?.name || 'Keine Rolle', permissions: teamUser.role?.permissions || [],
              userType: 'TEAM', forcePasswordChange: false
            };
          }
        }

        const customer = await prisma.customer.findUnique({ where: { email: credentials.email } });

        if (customer && customer.passwordHash) {
          const match = await bcrypt.compare(credentials.password, customer.passwordHash);
          if (match) {
            return {
              id: `CUST_${customer.id}`, dbId: customer.id, email: customer.email,
              firstName: customer.firstName, lastName: customer.lastName,
              roleName: 'Kunde', permissions: [], userType: 'CUSTOMER',
              companyName: customer.companyName, 
              forcePasswordChange: customer.forcePasswordChange // WICHTIG: Flag übergeben
            };
          }
        }
        return null;
      }
    })
  ],
  callbacks: {
    async jwt({ token, user }: any) {
      if (user) {
        token.dbId = user.dbId; token.firstName = user.firstName; token.lastName = user.lastName;
        token.roleName = user.roleName; token.permissions = user.permissions;
        token.userType = user.userType; token.companyName = user.companyName;
        token.forcePasswordChange = user.forcePasswordChange;
      }
      return token;
    },
    async session({ session, token }: any) {
      if (token) {
        session.user.id = token.dbId; session.user.firstName = token.firstName;
        session.user.lastName = token.lastName; session.user.roleName = token.roleName;
        session.user.permissions = token.permissions || []; session.user.userType = token.userType;
        session.user.companyName = token.companyName;
        session.user.forcePasswordChange = token.forcePasswordChange;
      }
      return session;
    }
  },
  pages: { signIn: "/login" },
  secret: process.env.NEXTAUTH_SECRET,
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
