
import { NextAuthOptions } from 'next-auth';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import CredentialsProvider from 'next-auth/providers/credentials';
import GoogleProvider from 'next-auth/providers/google';
import bcrypt from 'bcryptjs';
import { prisma } from '@/lib/db';

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  session: {
    strategy: 'jwt',
  },
  secret: process.env.NEXTAUTH_SECRET,
  providers: [
    CredentialsProvider({
      name: 'credentials',
      credentials: {
        email: { label: 'Email', type: 'email' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) {
          throw new Error('Missing credentials');
        }

        const user = await prisma.user.findUnique({
          where: { email: credentials.email },
          include: {
            partnerProfile: true,
            customerProfile: true,
          },
        });

        if (!user || !user.password) {
          throw new Error('Invalid credentials');
        }

        const isPasswordValid = await bcrypt.compare(credentials.password, user.password);

        if (!isPasswordValid) {
          throw new Error('Invalid credentials');
        }

        if (!user.isActive) {
          throw new Error('Account is deactivated');
        }

        // Update last login
        await prisma.user.update({
          where: { id: user.id },
          data: { lastLoginAt: new Date() },
        });

        return {
          id: user.id,
          email: user.email,
          name: user.name || undefined,
          role: user.role,
          companyName: user.companyName || undefined,
          image: user.image || undefined,
          trustScore: user.trustScore,
          isPartner: !!user.partnerProfile,
          isCustomer: !!user.customerProfile,
        };
      },
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID || '',
      clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',
    }),
  ],
  pages: {
    signIn: '/auth/signin',
  },
  callbacks: {
    async jwt({ token, user, account }) {
      if (user && account?.provider === 'credentials') {
        token.id = user.id;
        token.role = (user as any).role;
        token.companyName = (user as any).companyName;
        token.trustScore = (user as any).trustScore;
        token.isPartner = (user as any).isPartner;
        token.isCustomer = (user as any).isCustomer;
      }
      
      if (user && account?.provider === 'google') {
        // Handle Google sign-in
        const existingUser = await prisma.user.findUnique({
          where: { email: user.email! },
          include: {
            partnerProfile: true,
            customerProfile: true,
          },
        });

        if (existingUser) {
          token.id = existingUser.id;
          token.role = existingUser.role;
          token.companyName = existingUser.companyName || undefined;
          token.trustScore = existingUser.trustScore;
          token.isPartner = !!existingUser.partnerProfile;
          token.isCustomer = !!existingUser.customerProfile;
        } else {
          // Create new user for Google sign-in
          const newUser = await prisma.user.create({
            data: {
              email: user.email!,
              name: user.name || undefined,
              image: user.image || undefined,
              role: 'CUSTOMER',
              emailVerified: new Date(),
            },
          });
          
          await prisma.customer.create({
            data: {
              userId: newUser.id,
            },
          });

          token.id = newUser.id;
          token.role = newUser.role;
          token.isCustomer = true;
        }
      }

      return token;
    },
    async session({ session, token }) {
      if (token) {
        session.user.id = token.id as string;
        session.user.role = token.role as any;
        session.user.companyName = token.companyName as string;
        session.user.trustScore = token.trustScore as number;
        session.user.isPartner = token.isPartner as boolean;
        session.user.isCustomer = token.isCustomer as boolean;
      }
      return session;
    },
    async redirect({ url, baseUrl }) {
      // Allows relative callback URLs
      if (url.startsWith("/")) return `${baseUrl}${url}`;
      // Allows callback URLs on the same origin
      else if (new URL(url).origin === baseUrl) return url;
      return baseUrl;
    },
  },
  events: {
    async signIn({ user, account, profile }) {
      // Log sign-in event
      if (user.id) {
        await prisma.auditLog.create({
          data: {
            userId: user.id,
            entityType: 'user',
            entityId: user.id,
            action: 'signin',
            metadata: {
              provider: account?.provider,
              userAgent: 'system',
            },
          },
        });
      }
    },
    async signOut({ token }) {
      // Log sign-out event
      if (token?.id) {
        await prisma.auditLog.create({
          data: {
            userId: token.id as string,
            entityType: 'user',
            entityId: token.id as string,
            action: 'signout',
            metadata: {
              userAgent: 'system',
            },
          },
        });
      }
    },
  },
};
