// backend/src/admin/admin.module.ts
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, getModelByName } from '@adminjs/prisma'; // 👈 Add getModelByName
import AdminJS from 'adminjs';

// Register the adapter
AdminJS.registerAdapter({ Database, Resource });

@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 adminEmail =
        process.env.ADMINJS_EMAIL?.trim() || 'admin@dyolink.com';
      const adminPassword = process.env.ADMINJS_PASSWORD || 'admin123';
      if (email === adminEmail && password === adminPassword) {
        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' &&
              !process.env.ADMINJS_PASSWORD
            ) {
              console.warn(
                '⚠️  ADMINJS_PASSWORD is unset; AdminJS is using the local default. Set it in backend.env.',
              );
            }
            return {
              adminJsOptions: {
                rootPath: '/admin',
                resources: [
                  // ✅ Use getModelByName helper
                  {
                    resource: {
                      model: getModelByName('User'),
                      client: prisma,
                    },
                    options: {
                      properties: {
                        passwordHash: { isVisible: false },
                      },
                    },
                  },
                  {
                    resource: {
                      model: getModelByName('Organization'),
                      client: prisma,
                    },
                    options: {},
                  },
                  {
                    resource: {
                      model: getModelByName('OrganizationType'),
                      client: prisma,
                    },
                    options: {},
                  },
                  {
                    resource: {
                      model: getModelByName('Plan'),
                      client: prisma,
                    },
                    options: {},
                  },
                  {
                    resource: {
                      model: getModelByName('Membership'),
                      client: prisma,
                    },
                    options: {},
                  },
                  {
                    resource: {
                      model: getModelByName('Session'),
                      client: prisma,
                    },
                    options: {},
                  },
                ],
                componentLoader,
                dashboard: { component: Components.Dashboard },
                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,
                },
              },
            };
          },
        }),
      ],
    };
  }
}