import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

export interface BillingInfo {
  name: string; model: string; balance: string; currency: string; status: 'ok' | 'unknown'; consoleUrl: string; note: string;
}

@Injectable()
export class AdminBillingService {
  private readonly logger = new Logger(AdminBillingService.name);

  constructor(private readonly config: ConfigService) {}

  async getAllBilling(): Promise<{ providers: BillingInfo[] }> {
    const [deepseek, siliconflow] = await Promise.all([this.getDeepSeek(), this.getSiliconFlow()]);
    return { providers: [deepseek, siliconflow, this.getMiniMax(), this.getBaiduOcr()] };
  }

  private async getDeepSeek(): Promise<BillingInfo> {
    try {
      const apiKey = this.config.get<string>('ai.deepseek.apiKey') || process.env.DEEPSEEK_API_KEY || '';
      const r = await fetch('https://api.deepseek.com/user/balance', { headers: { Authorization: `Bearer ${apiKey}` } });
      const d = await r.json(); const b = d?.balance_infos?.[0]?.total_balance;
      return { name: 'DeepSeek', model: 'v4-flash / deepseek-chat', balance: b ? `¥${b}` : '—', currency: 'CNY', status: 'ok', consoleUrl: 'https://platform.deepseek.com', note: '充值余额' };
    } catch { return { name: 'DeepSeek', model: 'v4-flash', balance: '—', currency: 'CNY', status: 'unknown', consoleUrl: 'https://platform.deepseek.com', note: '查询失败' }; }
  }

  private async getSiliconFlow(): Promise<BillingInfo> {
    try {
      const apiKey = process.env.SILICONFLOW_API_KEY || '';
      const r = await fetch('https://api.siliconflow.cn/v1/user/info', { headers: { Authorization: `Bearer ${apiKey}` } });
      const d = await r.json(); const b = d?.data?.totalBalance;
      return { name: '硅基流动', model: 'BGE-M3 / BGE-Reranker', balance: b ? `¥${b}` : '—', currency: 'CNY', status: 'ok', consoleUrl: 'https://cloud.siliconflow.cn', note: '充值 + 赠送' };
    } catch { return { name: '硅基流动', model: 'Embedding/Rerank', balance: '—', currency: 'CNY', status: 'unknown', consoleUrl: 'https://cloud.siliconflow.cn', note: '查询失败' }; }
  }

  private getMiniMax(): BillingInfo { return { name: 'MiniMax', model: 'MiniMax 2.7', balance: '已到期', currency: '—', status: 'unknown', consoleUrl: 'https://platform.minimaxi.com', note: '已到期，已切换至 DeepSeek V4' }; }
  private getBaiduOcr(): BillingInfo { return { name: '百度 OCR', model: '通用文字识别', balance: '次数制', currency: 'calls', status: 'unknown', consoleUrl: 'https://console.bce.baidu.com', note: '需登录控制台查看' }; }
}
