import { Injectable } from '@nestjs/common';
import { AppConfigService } from '../config/config.service';
import { PrismaService } from '../../infrastructure/database/prisma.service';
import { LocalFilesystemStorageService } from '../storage/storage.service';
import { HealthResponseDto } from './health.dto';

@Injectable()
export class HealthService {
  constructor(
    private readonly configService: AppConfigService,
    private readonly prismaService: PrismaService,
    private readonly storageService: LocalFilesystemStorageService,
  ) {}

  async getHealth(): Promise<HealthResponseDto> {
    let databaseStatus: 'up' | 'down' = 'up';
    let storageStatus: 'up' | 'down' = 'up';

    try {
      await this.prismaService.$queryRawUnsafe('SELECT 1');
    } catch {
      databaseStatus = 'down';
    }

    try {
      await this.storageService.checkReadiness();
    } catch {
      storageStatus = 'down';
    }

    return {
      service: 'velody-backend',
      version: this.configService.appVersion,
      database: {
        status: databaseStatus,
      },
      storage: {
        status: storageStatus,
        root: this.storageService.root,
      },
      serverTime: new Date().toISOString(),
    };
  }
}
