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

@Controller("health")
export class HealthController {
  constructor(
    private readonly prisma: PrismaService,
    private readonly cache: CacheService,
    @Inject(Logger) private readonly logger: Logger
  ) {}

  @Get()
  async getHealth(): Promise<{ status: string; checks: Record<string, string> }> {
    const checks: Record<string, string> = {};

    // Database check
    try {
      await this.prisma.$queryRaw`SELECT 1`;
      checks.database = "ok";
    } catch (error) {
      this.logger.error({ error }, "Database health check failed");
      checks.database = "fail";
    }

    // Cache check
    try {
      const key = "health:check";
      await this.cache.set(key, { ok: true }, 5);
      const value = await this.cache.get<{ ok: boolean }>(key);
      checks.cache = value?.ok ? "ok" : "fail";
      await this.cache.del(key);
    } catch (error) {
      this.logger.error({ error }, "Cache health check failed");
      checks.cache = "fail";
    }

    const status = Object.values(checks).every(v => v === "ok") ? "ok" : "degraded";
    return { status, checks };
  }
}
