/* eslint-disable @typescript-eslint/no-namespace */
import { Injectable } from '@nestjs/common';
import { RedmineTypes } from '../models/redmine-types';
import { TimestampConverter } from '../utils/timestamp-converter';
import { IssueEnhancerInterface } from './issue-enhancer-interface';

export namespace TimePassedHighlightEnhancerNs {
  export type PriorityRules = {
    /** time in seconds */
    timePassed: number;
    priority: string;
  };
}

@Injectable()
export class TimePassedHighlightEnhancer implements IssueEnhancerInterface {
  name = 'activity-to-priority';

  private rules: TimePassedHighlightEnhancerNs.PriorityRules[] = [
    {
      timePassed: 60 * 60, // 1 час
      priority: 'hot',
    },
    {
      timePassed: 24 * 60 * 60, // 1 день,
      priority: 'warm',
    },
    {
      timePassed: 7 * 24 * 60 * 60, // 1 неделя
      priority: 'comfort',
    },
    {
      timePassed: 14 * 24 * 60 * 60, // 2 недели
      priority: 'breezy',
    },
  ];

  private otherPriority = 'cold';

  private keyNameForCssClass = 'timePassedClass';

  constructor() {
    this.rules = this.rules.sort((a, b) => {
      return a.timePassed - b.timePassed;
    });
  }

  async enhance(
    issue: RedmineTypes.ExtendedIssue,
  ): Promise<RedmineTypes.ExtendedIssue> {
    const nowTimestamp = new Date().getTime();
    if (!issue?.updated_on) return issue;
    for (let i = 0; i < this.rules.length; i++) {
      const rule = this.rules[i];
      if (
        nowTimestamp - TimestampConverter.toTimestamp(issue.updated_on) <=
        rule.timePassed * 1000
      ) {
        issue[this.keyNameForCssClass] = rule.priority;
        break;
      }
    }
    if (!issue[this.keyNameForCssClass]) {
      issue[this.keyNameForCssClass] = this.otherPriority;
    }
    return issue;
  }
}
