import { Injectable, Inject } from "@nestjs/common";
import { PrismaService } from "@bff/infra/database/prisma.service";
import { Logger } from "nestjs-pino";

export interface VoiceOptionsSettings {
  voiceMailEnabled: boolean;
  callWaitingEnabled: boolean;
  internationalRoamingEnabled: boolean;
  networkType: string;
}

@Injectable()
export class SimVoiceOptionsService {
  constructor(
    private readonly prisma: PrismaService,
    @Inject(Logger) private readonly logger: Logger
  ) {}

  /**
   * Get voice options for a SIM account
   * Returns null if no settings found
   */
  async getVoiceOptions(account: string): Promise<VoiceOptionsSettings | null> {
    try {
      const options = await this.prisma.simVoiceOptions.findUnique({
        where: { account },
      });

      if (!options) {
        this.logger.debug(`No voice options found in database for account ${account}`);
        return null;
      }

      return {
        voiceMailEnabled: options.voiceMailEnabled,
        callWaitingEnabled: options.callWaitingEnabled,
        internationalRoamingEnabled: options.internationalRoamingEnabled,
        networkType: options.networkType,
      };
    } catch (error) {
      this.logger.error(`Failed to get voice options for account ${account}`, { error });
      return null;
    }
  }

  /**
   * Save or update voice options for a SIM account
   */
  async saveVoiceOptions(account: string, settings: Partial<VoiceOptionsSettings>): Promise<void> {
    try {
      await this.prisma.simVoiceOptions.upsert({
        where: { account },
        create: {
          account,
          voiceMailEnabled: settings.voiceMailEnabled ?? false,
          callWaitingEnabled: settings.callWaitingEnabled ?? false,
          internationalRoamingEnabled: settings.internationalRoamingEnabled ?? false,
          networkType: settings.networkType ?? "4G",
        },
        update: {
          ...(settings.voiceMailEnabled !== undefined && {
            voiceMailEnabled: settings.voiceMailEnabled,
          }),
          ...(settings.callWaitingEnabled !== undefined && {
            callWaitingEnabled: settings.callWaitingEnabled,
          }),
          ...(settings.internationalRoamingEnabled !== undefined && {
            internationalRoamingEnabled: settings.internationalRoamingEnabled,
          }),
          ...(settings.networkType !== undefined && {
            networkType: settings.networkType,
          }),
        },
      });

      this.logger.log(`Saved voice options for account ${account}`, { settings });
    } catch (error) {
      this.logger.error(`Failed to save voice options for account ${account}`, {
        error,
        settings,
      });
      throw error;
    }
  }

  /**
   * Initialize voice options for a new SIM account
   */
  async initializeVoiceOptions(
    account: string,
    settings: {
      voiceMailEnabled?: boolean;
      callWaitingEnabled?: boolean;
      internationalRoamingEnabled?: boolean;
      networkType?: string;
    } = {}
  ): Promise<void> {
    await this.saveVoiceOptions(account, {
      voiceMailEnabled: settings.voiceMailEnabled ?? true,
      callWaitingEnabled: settings.callWaitingEnabled ?? true,
      internationalRoamingEnabled: settings.internationalRoamingEnabled ?? true,
      networkType: settings.networkType ?? "5G",
    });

    this.logger.log(`Initialized voice options for new SIM account ${account}`);
  }

  /**
   * Delete voice options for a SIM account (e.g., when SIM is cancelled)
   */
  async deleteVoiceOptions(account: string): Promise<void> {
    try {
      await this.prisma.simVoiceOptions.delete({
        where: { account },
      });

      this.logger.log(`Deleted voice options for account ${account}`);
    } catch (error) {
      // Silently ignore if record doesn't exist
      this.logger.debug(`Could not delete voice options for account ${account}`, { error });
    }
  }
}

