import { Repository } from 'typeorm';
import { AppDataSource } from '../index';
import { UserEmailSettings, EmailProvider } from '../entities/UserEmailSettings.entity';

export class UserEmailSettingsRepository {
  private repo: Repository<UserEmailSettings>;

  constructor() {
    this.repo = AppDataSource.getRepository(UserEmailSettings);
  }

  findByUserId(userId: string): Promise<UserEmailSettings | null> {
    return this.repo.findOne({ where: { userId } });
  }

  /**
   * Persist settings with UPDATE/INSERT instead of entity save().
   * Avoids TypeORM relation cascades that can hold long row locks on MySQL.
   */
  async upsert(userId: string, data: Partial<UserEmailSettings>): Promise<UserEmailSettings> {
    const existing = await this.findByUserId(userId);
    if (!existing) {
      try {
        await this.repo.insert({
          userId,
          provider: 'platform',
          smtpPort: 587,
          notificationsEnabled: true,
          sendFromUserEmail: false,
          sendReminderToGuest: true,
          sendReminderToHost: true,
          sendFollowUpEnabled: true,
          sendPostMeetingSurvey: true,
          ...data,
        });
      } catch (err) {
        const code =
          (err as { code?: string }).code ??
          (err as { driverError?: { code?: string } }).driverError?.code;
        if (code !== 'ER_DUP_ENTRY') {
          throw err;
        }
        await this.repo.update({ userId }, data);
      }
    } else {
      await this.repo.update({ userId }, data);
    }

    const saved = await this.findByUserId(userId);
    if (!saved) {
      throw new Error('Failed to persist email settings.');
    }
    return saved;
  }
}

export type { EmailProvider };
