import { Injectable, Logger } from '@nestjs/common'; import { SecretService } from '../global/secret/secret.service'; const DEFAULT_SHORTENER_API_URL = 'https://go.dahyeon.us/api/shorten'; const DEFAULT_SHORTENER_BASE_URL = 'https://go.dahyeon.us'; const DEFAULT_TARGET_BASE_URL = 'https://lolympus.dahyeon.us'; const DEFAULT_TIMEOUT_MS = 1500; interface ShortenMatchLinkParams { matchId: string; shortCode: string | undefined; } interface ShortenerResponseBody { shortUrl?: unknown; } @Injectable() export class DakaoUrlShortenerService { private readonly logger = new Logger(DakaoUrlShortenerService.name); constructor(private readonly secretService: SecretService) {} public async shortenMatchLink( params: ShortenMatchLinkParams, ): Promise { const shortCode = params.shortCode?.trim().toUpperCase(); if (!shortCode) return undefined; const token = await this.resolveToken(); if (!token) return undefined; const slug = `${this.resolveSlugPrefix()}${shortCode}`; const requestBody = { slug, url: this.buildMatchDetailUrl(params.matchId), redirectStatus: 302, expiresAt: null, }; const controller = new AbortController(); const timeout = setTimeout( () => controller.abort(), this.resolveTimeoutMs(), ); try { const response = await fetch(this.resolveApiUrl(), { method: 'POST', headers: { Accept: 'application/json', Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', }, body: JSON.stringify(requestBody), signal: controller.signal, }); if (response.status === 409) { return this.buildShortUrl(slug); } if (!response.ok) { await this.logFailedResponse(response, slug); return undefined; } const payload = await this.parseResponseBody(response); const shortUrl = payload?.shortUrl; return typeof shortUrl === 'string' && shortUrl.trim() ? shortUrl.trim() : this.buildShortUrl(slug); } catch (error) { this.logger.warn( `URL shortener request failed for slug="${slug}": ${error instanceof Error ? error.message : String(error)}`, ); return undefined; } finally { clearTimeout(timeout); } } private async resolveToken(): Promise { try { const token = await this.secretService.get( 'URL_SHORTENER_TOKEN', '', ); return token.trim() || undefined; } catch (error) { this.logger.warn( `URL shortener token unavailable: ${error instanceof Error ? error.message : String(error)}`, ); return undefined; } } private resolveSlugPrefix(): 'lmtp' | 'lmts' { const nodeEnv = process.env.NODE_ENV?.trim().toLowerCase(); return nodeEnv === 'prod' || nodeEnv === 'production' ? 'lmtp' : 'lmts'; } public buildMatchDetailUrl(matchId: string): string { return `${this.resolveTargetBaseUrl()}/match/${encodeURIComponent(matchId)}`; } private buildShortUrl(slug: string): string { return `${this.resolveShortenerBaseUrl()}/${encodeURIComponent(slug)}`; } private resolveApiUrl(): string { return ( process.env.URL_SHORTENER_API_URL?.trim() || DEFAULT_SHORTENER_API_URL ); } private resolveShortenerBaseUrl(): string { return ( this.normalizeBaseUrl(process.env.URL_SHORTENER_BASE_URL) ?? this.normalizeOrigin(this.resolveApiUrl()) ?? DEFAULT_SHORTENER_BASE_URL ); } private resolveTargetBaseUrl(): string { return ( this.normalizeBaseUrl(process.env.URL_SHORTENER_TARGET_BASE_URL) ?? this.normalizeBaseUrl(process.env.WEB_ORIGIN) ?? DEFAULT_TARGET_BASE_URL ); } private resolveTimeoutMs(): number { const configured = Number(process.env.URL_SHORTENER_TIMEOUT_MS); return Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_TIMEOUT_MS; } private normalizeBaseUrl(value: string | undefined): string | undefined { const raw = value?.split(',')[0]?.trim(); if (!raw) return undefined; try { const url = new URL(raw); const pathname = url.pathname.replace(/\/+$/u, ''); return `${url.origin}${pathname}`; } catch { return undefined; } } private normalizeOrigin(value: string): string | undefined { try { return new URL(value).origin; } catch { return undefined; } } private async parseResponseBody( response: Response, ): Promise { try { return (await response.json()) as ShortenerResponseBody; } catch { return undefined; } } private async logFailedResponse( response: Response, slug: string, ): Promise { const body = await response.text().catch(() => ''); this.logger.warn( `URL shortener returned ${response.status} for slug="${slug}"${body ? `: ${body.slice(0, 200)}` : ''}`, ); } }