import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '@core/database/prisma/prisma.service';

/**
 * 内部 app 平台主服务
 *
 * 骨架阶段：仅暴露最小可调用入口，详细业务逻辑见各专项 service
 * （token.service / slug.service / 后续 deploy.service / env.service）。
 *
 * 详见 docs/modules/internal-app-platform/07-api.md
 */
@Injectable()
export class InternalAppPlatformService {
  private readonly logger = new Logger(InternalAppPlatformService.name);

  constructor(private readonly prisma: PrismaService) {}

  /**
   * 解析当前请求 user → employeeSlug
   *
   * 三层 fallback：
   * 1. req.user.employeeSlug 直接给（Phase 1 Entra middleware 注入）
   * 2. req.user.id 查 employee_slug_bindings 反查（Phase 0 兜底——
   *    PoC 员工的 binding 由 IT 手工 SQL 建好，详见 runbook §1.2）
   * 3. 都没有 → 返回 null，调用方决定怎么响应
   */
  async resolveEmployeeSlug(user: {
    id?: string;
    userId?: string;
    employeeSlug?: string;
  }): Promise<string | null> {
    if (user.employeeSlug) return user.employeeSlug;
    // 兼容两种 user 形状：Entra middleware 用 .id，本项目 JWT strategy 注入 .userId
    const userId = user.id ?? user.userId;
    if (!userId) return null;
    const binding = await this.prisma.employeeSlugBinding.findUnique({
      where: { userId },
      select: { employeeSlug: true, organizationId: true },
    });
    return binding?.employeeSlug ?? null;
  }

  /**
   * 列出员工自己的 app（PRD F2.3）
   * 骨架返回空数组，真实实现在 Phase 0 末期补
   */
  async listMyApps(employeeSlug: string, includeDestroyed = false) {
    this.logger.debug(
      `listMyApps employeeSlug=${employeeSlug} includeDestroyed=${includeDestroyed}`,
    );

    const where: { employeeSlug: string; status?: { not: 'DESTROYED' } } = {
      employeeSlug,
    };
    if (!includeDestroyed) {
      where.status = { not: 'DESTROYED' };
    }

    return this.prisma.internalApp.findMany({
      where,
      orderBy: { lastDeployedAt: 'desc' },
    });
  }
}
