import { Controller, Get, HttpStatus, Req, Res } from '@nestjs/common';
import { FastifyRequest, FastifyReply } from 'fastify';
import { pathExistsSync, readFileSync } from 'fs-extra';
import { resolve } from 'path';
import * as yaml from 'js-yaml';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get('/appdata')
  async getAppData(@Req() request: FastifyRequest, @Res() response: FastifyReply) {
    const result = await this.appService.getAppData(request, response);
    response.status(HttpStatus.OK).send(result);
  }

  @Get('/app/environment')
  async getAppEnvironment(): Promise<Record<string, unknown>> {
    try {
      const path = resolve(__dirname, '../configs/app.environment.yaml');
      if (pathExistsSync(path)) {
        const config = readFileSync(path, 'utf-8');
        const json = yaml.load(config);
        return json;
      }
    } catch (err) {
      throw new Error(`app.environment.yaml 读取失败：${err.message}`);
    }
    return {};
  }
}
