import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common';
import { UsersRepositoryService } from '../../repositories/users/users.repository.service';
import { TemplateFile } from './types/types';
import { Context } from '../../common/log';
import { makeErrorResponse } from '../../common/error/makeErrorResponse';
import { TemplateFilesRepositoryService } from '../../repositories/template_files/template_files.repository.service';

@Injectable()
export class TemplatesService {
  private readonly logger = new Logger(TemplatesService.name);
  constructor(
    private readonly usersRepository: UsersRepositoryService,
    private readonly templateFilesRepository: TemplateFilesRepositoryService,
  ) {}

  /**
   * アカウント内のテンプレートファイルの一覧を取得する
   * @param context
   * @param externalId
   * @returns templates
   */
  async getTemplates(
    context: Context,
    externalId: string,
  ): Promise<TemplateFile[]> {
    this.logger.log(
      `[IN] [${context.getTrackingId()}] ${
        this.getTemplates.name
      } | params: { externalId: ${externalId} };`,
    );

    try {
      const { account_id: accountId } =
        await this.usersRepository.findUserByExternalId(context, externalId);

      const templateFileRecords =
        await this.templateFilesRepository.getTemplateFiles(context, accountId);

      // DBから取得したテンプレートファイルのレコードをレスポンス用に整形する
      const resTemplates = templateFileRecords.map((templateFile) => ({
        id: templateFile.id,
        name: templateFile.file_name,
      }));

      return resTemplates;
    } catch (e) {
      this.logger.error(`[${context.getTrackingId()}] error=${e}`);
      throw new HttpException(
        makeErrorResponse('E009999'),
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    } finally {
      this.logger.log(
        `[OUT] [${context.getTrackingId()}] ${this.getTemplates.name}`,
      );
    }
  }
}
