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 { 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 profileIdSetting = await prisma.setting.findUnique({
            where: { slug: 'mail-profile-id' },
            select: { value: true },
          });

          const profileId = Number(profileIdSetting?.value);

          if (!profileId || profileId <= 0) {
            return { global: true, type: 'SMTP', host: 'localhost', port: 1025, secure: false, username: '', password: '' } as MailModuleOptions;
          }

          const profile = await prisma.mail_profile.findUnique({
            where: { id: profileId },
          });

          if (!profile) {
            return { global: true, type: 'SMTP', host: 'localhost', port: 1025, secure: false, username: '', password: '' } as MailModuleOptions;
          }

          const base: MailModuleOptions = { global: true } as MailModuleOptions;

          switch (profile.provider) {
            case 'GMAIL':
              return Object.assign(base, {
                type: 'GMAIL',
                clientId: profile.gmail_client_id ?? '',
                clientSecret: profile.gmail_client_secret ?? '',
                refreshToken: profile.gmail_refresh_token ?? '',
                from: profile.from_email,
              });
            case 'SMTP':
              return Object.assign(base, {
                type: 'SMTP',
                host: profile.smtp_host ?? 'localhost',
                port: profile.smtp_port ?? 1025,
                secure: profile.smtp_secure ?? false,
                username: profile.smtp_username ?? '',
                password: profile.smtp_password ?? '',
              });
            case 'SES':
              return Object.assign(base, {
                type: 'SES',
                region: profile.ses_region ?? '',
                accessKeyId: profile.ses_access_key_id ?? '',
                secretAccessKey: profile.ses_secret_access_key ?? '',
                from: profile.from_email,
              });
            default:
              return { global: true, type: 'SMTP', host: 'localhost', port: 1025, secure: false, username: '', password: '' } as MailModuleOptions;
          }
        } catch (error) {
          console.error('Error loading mail settings:', error);
          return { global: true, type: 'SMTP', host: 'localhost', port: 1025, secure: false, username: '', password: '' } as MailModuleOptions;
        }
      }
    })),
    forwardRef(() => MailSentModule),
    forwardRef(() => PrismaModule),
    forwardRef(() => PaginationModule),
    forwardRef(() => LocaleModule),
    forwardRef(() => SettingModule),
  ],
  controllers: [MailController],
  providers: [MailService],
  exports: [MailService],
})
export class MailModule { }
