import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SettingsService } from './settings.service';

@Injectable()
export class OAuthIssuerService {
  constructor(
    private readonly settings: SettingsService,
    private readonly config: ConfigService
  ) {}

  async resolveIssuer(): Promise<string> {
    const fromDb = (await this.settings.getValue('PUBLIC_API_URL', '')).trim();
    if (fromDb) {
      return fromDb.replace(/\/+$/, '');
    }

    const fromEnv = this.config.get<string>('PUBLIC_API_URL')?.trim();
    if (fromEnv) {
      return fromEnv.replace(/\/+$/, '');
    }

    const domain = (await this.settings.getValue('PROJECT_DOMAIN', 'id.lendry.ru')).trim();
    if (domain.startsWith('http://') || domain.startsWith('https://')) {
      return domain.replace(/\/+$/, '');
    }

    return `https://${domain.replace(/^\/+/, '')}`;
  }
}
