import { DynamicModule, Module } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { componentLoader, Components } from './components';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { Database, Resource } from '@adminjs/prisma';
import AdminJS from 'adminjs';
import { buildAdminResources } from './resources';

AdminJS.registerAdapter({ Database, Resource });

const LOCAL_DEFAULT_ADMIN_PASSWORD = 'admin123';
const LOCAL_DEFAULT_ADMIN_EMAIL = 'admin@dyolink.com';

@Module({
  imports: [ConfigModule],
})
export class AdminModule {
  static async forRoot(): Promise<DynamicModule> {
    const { AdminModule: AdminJSModule } = await import('@adminjs/nestjs');

    const authenticate = async (email: string, password: string) => {
      const isProduction = process.env.NODE_ENV === 'production';
      const adminEmail =
        process.env.ADMINJS_EMAIL?.trim() || LOCAL_DEFAULT_ADMIN_EMAIL;
      const adminPassword = process.env.ADMINJS_PASSWORD;

      if (isProduction) {
        if (
          !adminPassword ||
          adminPassword === LOCAL_DEFAULT_ADMIN_PASSWORD
        ) {
          return null;
        }
      }

      const effectivePassword =
        adminPassword || LOCAL_DEFAULT_ADMIN_PASSWORD;

      if (email === adminEmail && password === effectivePassword) {
        return { email, role: 'admin' };
      }
      return null;
    };

    return {
      module: AdminModule,
      imports: [
        await AdminJSModule.createAdminAsync({
          imports: [ConfigModule],
          inject: [PrismaService, ConfigService],
          useFactory: (prisma: PrismaService, config: ConfigService) => {
            const cookieSecure = config.get<boolean>('cookie.secure') === true;
            const sessionSecret =
              config.get<string>('jwt.secret') ||
              config.get('JWT_SECRET') ||
              'secret-key-change-this';

            if (process.env.NODE_ENV === 'production') {
              const adminPassword = process.env.ADMINJS_PASSWORD;
              if (
                !adminPassword ||
                adminPassword === LOCAL_DEFAULT_ADMIN_PASSWORD
              ) {
                console.error(
                  '❌ AdminJS: ADMINJS_PASSWORD is missing or still the local default. Login is disabled until you set a strong password in backend.env.',
                );
              }
            }

            return {
              adminJsOptions: {
                rootPath: '/admin',
                resources: buildAdminResources(prisma),
                componentLoader,
                dashboard: {
                  component: Components.Dashboard,
                  handler: async () => {
                    const [clinicType, labType] = await Promise.all([
                      prisma.organizationType.findUnique({
                        where: { name: 'CLINIC' },
                      }),
                      prisma.organizationType.findUnique({
                        where: { name: 'LAB' },
                      }),
                    ]);

                    const [clinics, labs, users, labCases] = await Promise.all([
                      clinicType
                        ? prisma.organization.count({
                            where: { typeId: clinicType.id },
                          })
                        : Promise.resolve(0),
                      labType
                        ? prisma.organization.count({
                            where: { typeId: labType.id },
                          })
                        : Promise.resolve(0),
                      prisma.user.count(),
                      prisma.labCase.count(),
                    ]);

                    return { clinics, labs, users, labCases };
                  },
                },
                branding: {
                  companyName: 'DyoLink Admin',
                  logo: false,
                  softwareBrothers: false,
                },
              },
              auth: {
                authenticate,
                cookieName: 'dyolink-admin',
                cookiePassword: sessionSecret,
              },
              sessionOptions: {
                resave: false,
                saveUninitialized: false,
                secret: sessionSecret,
                cookie: {
                  httpOnly: true,
                  sameSite: 'lax' as const,
                  secure: cookieSecure,
                },
              },
            };
          },
        }),
      ],
    };
  }
}
