import { LocaleModule } from '@hed-hog/api-locale';
import { MailModule as MailMainModule, MailModuleOptions } from '@hed-hog/api-mail';
import { PaginationModule } from '@hed-hog/api-pagination';
import { PrismaModule, PrismaService } from '@hed-hog/api-prisma';
import { BadRequestException, forwardRef, Module } from '@nestjs/common';
import { MailSentModule } from '../mail-sent/mail-sent.module';
import { SettingModule } from '../setting/setting.module';
import { MailController } from './mail.controller';
import { MailService } from './mail.service';

@Module({
  imports: [
    forwardRef(() => MailMainModule.forRootAsync({
      imports: [PrismaModule],
      inject: [PrismaService],
      useFactory: async (prisma: PrismaService) => {
        try {
          const mailSettings = await prisma.setting.findMany({
            where: {
              slug: {
                in: [

                  'mail-provider',
                  'mail-from',
                  'mail-gmail-client-id',
                  'mail-gmail-client-secret',
                  'mail-gmail-refresh-token',
                  'mail-smtp-host',
                  'mail-smtp-port',
                  'mail-smtp-secure',
                  'mail-client-secret',
                  'mail-client-secret',
                  'mail-aws-access-key-id',
                  'mail-aws-secret-access-key',
                  'mail-aws-region'
                ]
              }
            },
            select: {
              slug: true,
              value: true,
            }
          });

          const settings = new Map<string, string>();

          for (const setting of mailSettings) {
            settings.set(setting.slug, setting.value);
          }

          const config: MailModuleOptions = {
            global: true,
          } as MailModuleOptions;

          switch (settings.get('mail-provider')) {
            case 'GMAIL':
              Object.assign(config, {
                type: 'GMAIL',
                clientId: settings.get('mail-gmail-client-id'),
                clientSecret: settings.get('mail-gmail-client-secret'),
                refreshToken: settings.get('mail-gmail-refresh-token'),
                from: settings.get('mail-from'),
              });
              break;
            case 'SMTP':
              Object.assign(config, {
                type: 'SMTP',
                host: settings.get('mail-smtp-host'),
                port: Number(settings.get('mail-smtp-port')),
                secure: settings.get('mail-smtp-secure') === 'true',
                username: settings.get('mail-from'),
                password: settings.get('mail-client-secret'),
              });
              break;
            case 'SES':
              Object.assign(config, {
                type: 'SES',
                region: settings.get('mail-aws-region'),
                accessKeyId: settings.get('mail-aws-access-key-id'),
                secretAccessKey: settings.get('mail-aws-secret-access-key'),
                from: settings.get('mail-from'),
              });
              break;
            default:
              throw new BadRequestException(`Invalid mail provider: ${settings.get('mail-provider')}`);
          }

          return config;
        }

        catch (error) {
          console.error('Error loading mail settings:', error);
          throw error;
        }
      }
    })),
    forwardRef(() => MailSentModule),
    forwardRef(() => PrismaModule),
    forwardRef(() => PaginationModule),
    forwardRef(() => LocaleModule),
    forwardRef(() => SettingModule),
  ],
  controllers: [MailController],
  providers: [MailService],
  exports: [MailService],
})
export class MailModule { }
