import { NextAuthOptions } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { compare } from 'bcryptjs';
import { db } from '@/lib/db';

export const authOptions: NextAuthOptions = {
  session: {
    strategy: 'jwt',
    maxAge: 30 * 24 * 60 * 60, // 30 days
  },
  pages: {
    signIn: '/login',
    error: '/login',
  },
  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('Email and password are required');
        }

        const user = await db.user.findFirst({
          where: {
            email: credentials.email,
            isActive: true,
          },
          include: {
            organization: {
              select: {
                id: true,
                name: true,
              },
            },
            sites: {
              where: {
                isActive: true,
              },
              select: {
                id: true,
                name: true,
              },
              take: 1,
            },
          },
        });

        if (!user) {
          throw new Error('Invalid email or password');
        }

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

        if (!isPasswordValid) {
          throw new Error('Invalid email or password');
        }

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

        // Get the first site if available
        const primarySite = user.sites[0];

        return {
          id: user.id,
          email: user.email,
          name: `${user.firstName} ${user.lastName}`,
          role: user.role,
          organizationId: user.organizationId,
          organizationName: user.organization.name,
          siteId: primarySite?.id ?? null,
          siteName: primarySite?.name ?? null,
        };
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user, trigger, session }) {
      if (user) {
        token.id = user.id;
        token.role = user.role;
        token.organizationId = user.organizationId;
        token.organizationName = user.organizationName;
        token.siteId = user.siteId;
        token.siteName = user.siteName;
      }

      // Handle session update (e.g., when user changes site)
      if (trigger === 'update' && session) {
        if (session.siteId !== undefined) {
          token.siteId = session.siteId;
        }
        if (session.siteName !== undefined) {
          token.siteName = session.siteName;
        }
      }

      return token;
    },
    async session({ session, token }) {
      if (token) {
        session.user.id = token.id as string;
        session.user.role = token.role as string;
        session.user.organizationId = token.organizationId as string;
        session.user.organizationName = token.organizationName as string;
        session.user.siteId = token.siteId as string | null;
        session.user.siteName = token.siteName as string | null;
      }
      return session;
    },
  },
};

export default authOptions;
