import { Injectable } from '@nestjs/common';
import { RedmineTypes } from '../models/redmine-types';
import { IssueEnhancerInterface } from './issue-enhancer-interface';

@Injectable()
export class TimestampEnhancer implements IssueEnhancerInterface {
  name = 'timestamp';

  async enhance(
    issue: RedmineTypes.Issue,
  ): Promise<RedmineTypes.Issue & Record<string, any>> {
    return this.createTimestamp(this.enhanceJournal(issue), [
      'closed_on',
      'created_on',
      'updated_on',
    ]) as RedmineTypes.Issue & Record<string, any>;
  }

  private enhanceJournal(issue: Record<string, any>): Record<string, any> {
    if (!issue.journals || issue.journals.length === 0) {
      return issue;
    }
    const journals = issue.journals;
    for (let i = 0; i < journals.length; i++) {
      journals[i] = this.createTimestamp(journals[i], ['created_on']);
    }
    return issue;
  }

  private createTimestamp(
    issue: Record<string, any>,
    fieldNames: string[],
  ): Record<string, any> {
    for (let i = 0; i < fieldNames.length; i++) {
      const fieldName = fieldNames[i];
      if (issue[fieldName]) {
        issue[`${fieldName}_timestamp`] = new Date(issue[fieldName]).getTime();
      }
    }
    return issue;
  }
}
