import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { Integration } from '@prisma/client';
import { IntegrationManager } from '@gitroom/nestjs-libraries/integrations/integration.manager';
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
import {
  AuthTokenDetails,
  SocialProvider,
} from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';
import { TemporalService } from 'nestjs-temporal-core';

@Injectable()
export class RefreshIntegrationService {
  constructor(
    private _integrationManager: IntegrationManager,
    @Inject(forwardRef(() => IntegrationService))
    private _integrationService: IntegrationService,
    private _temporalService: TemporalService
  ) {}

  async refresh(
    integration: Integration,
    cause = ''
  ): Promise<false | AuthTokenDetails> {
    return this._integrationService.withIntegrationLock(
      integration.id,
      async (freshIntegration, tx) => {
        if (!freshIntegration) {
          return false as const;
        }

        const callerSnapshotRefreshToken = integration.refreshToken;
        const storedRefreshToken = freshIntegration.refreshToken;
        const now = Date.now();
        const storedExpiration = freshIntegration.tokenExpiration
          ? new Date(freshIntegration.tokenExpiration).getTime()
          : 0;
        const fiveMinutesMs = 5 * 60 * 1000;

        // If another process already refreshed and the stored token is valid for > 5 minutes
        if (
          storedRefreshToken &&
          storedRefreshToken !== callerSnapshotRefreshToken &&
          storedExpiration > now + fiveMinutesMs
        ) {
          const secondsLeft = Math.max(
            0,
            Math.floor((storedExpiration - now) / 1000)
          );
          return {
            accessToken: freshIntegration.token,
            refreshToken: storedRefreshToken,
            expiresIn: secondsLeft,
            id: freshIntegration.internalId,
            name: freshIntegration.name,
            picture: freshIntegration.picture || '',
            username: freshIntegration.profile || '',
          };
        }

        const socialProvider = this._integrationManager.getSocialIntegration(
          freshIntegration.providerIdentifier
        );

        // Call refreshProcess with the re-read row/token (never the snapshot token)
        const refresh = await this.refreshProcess(
          freshIntegration,
          socialProvider,
          cause,
          callerSnapshotRefreshToken
        );

        if (!refresh) {
          return false as const;
        }

        // Persist the new tokens before the lock is released. The full update (picture re-upload, profile, sibling
        // channels) is best effort: TikTok has already invalidated the old refresh token, so a failure there must
        // never lose the new one. The minimal update below runs last, on the lock transaction, and always commits.
        try {
          await this._integrationService.createOrUpdateIntegration(
            undefined,
            !!socialProvider.oneTimeToken,
            freshIntegration.organizationId,
            freshIntegration.name,
            freshIntegration.picture!,
            'social',
            freshIntegration.internalId,
            freshIntegration.providerIdentifier,
            refresh.accessToken,
            refresh.refreshToken,
            refresh.expiresIn,
            refresh.username || freshIntegration.profile
          );
        } catch (err) {
          console.error(
            `Refresh of ${freshIntegration.providerIdentifier} channel ${freshIntegration.id}: profile update failed, tokens still saved`,
            err instanceof Error ? err.message : err
          );
        }

        await tx.integration.update({
          where: { id: freshIntegration.id },
          data: {
            token: refresh.accessToken,
            refreshToken: refresh.refreshToken,
            ...(refresh.expiresIn
              ? {
                  tokenExpiration: new Date(
                    Date.now() + refresh.expiresIn * 1000
                  ),
                }
              : {}),
            refreshNeeded: false,
            deletedAt: null,
          },
        });

        return refresh;
      }
    );
  }

  public async setBetweenSteps(integration: Integration, cause = '') {
    await this._integrationService.setBetweenRefreshSteps(integration.id);
    await this._integrationService.informAboutRefreshError(
      integration.organizationId,
      integration,
      cause
    );
  }

  public async startRefreshWorkflow(
    orgId: string,
    id: string,
    integration: SocialProvider
  ) {
    if (!integration.refreshCron) {
      return false;
    }

    return this._temporalService.client
      .getRawClient()
      ?.workflow.start(`refreshTokenWorkflow`, {
        workflowId: `refresh_${id}`,
        args: [{ integrationId: id, organizationId: orgId }],
        taskQueue: 'main',
        workflowIdConflictPolicy: 'TERMINATE_EXISTING',
      });
  }

  private async refreshProcess(
    integration: Integration,
    socialProvider: SocialProvider,
    cause = '',
    snapshotRefreshToken = ''
  ): Promise<AuthTokenDetails | false> {
    const refresh: false | AuthTokenDetails = await socialProvider
      .refreshToken(integration.refreshToken)
      .catch((err) => false);

    if (!refresh || !refresh.accessToken) {
      // Check if the stored row has meanwhile changed to a newer refresh token
      const currentRow = await this._integrationService.getIntegrationById(
        integration.organizationId,
        integration.id
      );

      const hasNewerToken =
        currentRow?.refreshToken &&
        currentRow.refreshToken !== integration.refreshToken &&
        (!snapshotRefreshToken ||
          currentRow.refreshToken !== snapshotRefreshToken);

      if (hasNewerToken) {
        // Do not mark refreshNeeded or disconnect if another process has updated the token
        return false;
      }

      await this._integrationService.refreshNeeded(
        integration.organizationId,
        integration.id
      );

      await this._integrationService.informAboutRefreshError(
        integration.organizationId,
        integration,
        cause
      );

      await this._integrationService.disconnectChannel(
        integration.organizationId,
        integration
      );

      return false;
    }

    if (
      !socialProvider.reConnect ||
      integration.rootInternalId === integration.internalId
    ) {
      return refresh;
    }

    const reConnect = await socialProvider.reConnect(
      integration.rootInternalId,
      integration.internalId,
      refresh.accessToken
    );

    return {
      ...refresh,
      ...reConnect,
    };
  }
}
