import { Injectable } from '@nestjs/common';
import axios from 'axios';

class SimpleIssueUpdater {
  constructor(
    private userApiKey: string,
    private updater: IssuesUpdaterService,
  ) {}

  async updateIssue(
    issueId: number,
    issue: Record<string, any>,
  ): Promise<boolean> {
    return await this.updater.updateIssue(issueId, issue, this.userApiKey);
  }
}

@Injectable()
export class IssuesUpdaterService {
  constructor(private redminePublicUrl: string) {}

  createSimpleUpdater(userApiKey: string): SimpleIssueUpdater {
    return new SimpleIssueUpdater(userApiKey, this);
  }

  async updateIssue(
    issueId: number,
    issue: Record<string, any>,
    userApiKey: string,
  ): Promise<boolean> {
    const url = this.getUrl(issueId);
    const data = { issue: issue };
    const resp = await axios.put(url, data, {
      headers: { 'X-Redmine-API-Key': userApiKey },
    });
    return Boolean(resp);
  }

  private getUrl(issueId: number): string {
    return `${this.redminePublicUrl}/issues/${issueId}.json`;
  }
}
