/*
 * Copyright (C) 2018-2022 Open StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {Api, IssueState, Scope} from '@openstapps/gitlab-api';
import {Logger} from '@openstapps/logger';
import {CONCURRENCY, GROUPS, LAST_MEETING, NOTE_PREFIX} from '../configuration.js';
import isBefore from 'date-fns/isBefore';
import {mapAsyncLimit} from '@openstapps/collection-utils';

/**
 * Remove label `meeting` from closed issues
 * @param api Instance of GitLabAPI to send requests with
 */
export async function removeLabel(api: Api) {
  const issues = await mapAsyncLimit(
    GROUPS,
    async groupId => {
      return api.getIssues({
        groupId: groupId,
        state: IssueState.CLOSED,
      });
    },
    CONCURRENCY,
  ).then(it => it.flat());

  Logger.log(`Fetched ${issues.length} closed issue(s).`);

  await mapAsyncLimit(
    issues,
    async issue => {
      if (
        issue.labels.includes('meeting') &&
        issue.closed_at !== null &&
        isBefore(new Date(issue.closed_at), LAST_MEETING)
      ) {
        Logger.info(
          `Issue ${issue.title} is closed before last meeting and has label "meeting". Removing it.`,
        );

        await api.createNote(
          issue.project_id,
          Scope.ISSUES,
          issue.iid,
          `${NOTE_PREFIX} Removed label \`meeting\` automatically.
/unlabel ~meeting`,
        );
      }
    },
    CONCURRENCY,
  );

  Logger.ok('Label `meeting` has been removed from closed issues.');
}
