import { PlainVerifier } from "../code_verifiers/plain.verifier.js";
import { S256Verifier } from "../code_verifiers/S256.verifier.js";
import { CodeChallengeMethod, ICodeChallenge } from "../code_verifiers/verifier.js";
import { OAuthAuthCode } from "../entities/auth_code.entity.js";
import { OAuthClient } from "../entities/client.entity.js";
import { OAuthScope } from "../entities/scope.entity.js";
import { OAuthUserIdentifier } from "../entities/user.entity.js";
import { OAuthException } from "../exceptions/oauth.exception.js";
import { OAuthTokenRepository } from "../repositories/access_token.repository.js";
import { OAuthAuthCodeRepository } from "../repositories/auth_code.repository.js";
import { OAuthClientRepository } from "../repositories/client.repository.js";
import { OAuthScopeRepository } from "../repositories/scope.repository.js";
import { OAuthUserRepository } from "../repositories/user.repository.js";
import { AuthorizationRequest } from "../requests/authorization.request.js";
import { RequestInterface } from "../requests/request.js";
import { RedirectResponse } from "../responses/redirect.response.js";
import { OAuthResponse, ResponseInterface } from "../responses/response.js";
import { timingSafeCompare } from "../utils/compare.js";
import { DateInterval } from "../utils/date_interval.js";
import { JwtInterface } from "../utils/jwt.js";
import { AbstractAuthorizedGrant } from "./abstract/abstract_authorized.grant.js";
import { GrantIdentifier } from "./abstract/grant.interface.js";
import { AuthorizationServerOptions } from "../options.js";
import { AuthCodeEncoder, JwtAuthCodeEncoder, OpaqueAuthCodeEncoder } from "./encoders/auth_code_encoder.js";

export interface PayloadAuthCode {
  client_id: string;
  auth_code_id: string;
  expire_time: number;
  scopes: string[];
  user_id?: OAuthUserIdentifier | null;
  redirect_uri?: string | null;
  code_challenge?: string | null;
  code_challenge_method?: CodeChallengeMethod | null;
  audience?: string[] | string | null;
}
/** @deprecated use `PayloadAuthCode` instead */
export interface IAuthCodePayload extends PayloadAuthCode {}

export const REGEXP_CODE_VERIFIER = /^[A-Za-z0-9-._~]{43,128}$/;

export const REGEX_ACCESS_TOKEN = /[A-Za-z0-9\-._~+\/]+=*/;

export class AuthCodeGrant extends AbstractAuthorizedGrant {
  readonly identifier: GrantIdentifier = "authorization_code";

  protected authCodeTTL: DateInterval = new DateInterval("15m");

  private codeChallengeVerifiers = {
    plain: new PlainVerifier(),
    S256: new S256Verifier(),
  };

  private authCodeEncoder: AuthCodeEncoder;

  constructor(
    protected readonly authCodeRepository: OAuthAuthCodeRepository,
    protected readonly userRepository: OAuthUserRepository,
    clientRepository: OAuthClientRepository,
    tokenRepository: OAuthTokenRepository,
    scopeRepository: OAuthScopeRepository,
    jwt: JwtInterface,
    options: AuthorizationServerOptions,
  ) {
    super(clientRepository, tokenRepository, scopeRepository, jwt, options);
    this.authCodeEncoder = this.options.useOpaqueAuthorizationCodes
      ? new OpaqueAuthCodeEncoder(this.authCodeRepository)
      : new JwtAuthCodeEncoder(
          payload => this.encrypt(payload),
          rawCode => this.decrypt(rawCode),
          rawCode => this.jwt.decode(rawCode),
        );
  }

  async respondToAccessTokenRequest(req: RequestInterface, accessTokenTTL: DateInterval): Promise<ResponseInterface> {
    const client = await this.validateClient(req);

    const incomingRawAuthCodeValue = this.getRequestParameter("code", req);

    if (!incomingRawAuthCodeValue) throw OAuthException.invalidParameter("code");

    const { properties: authCodeProperties, authCode: preloadedAuthCode } =
      await this.resolveAuthCodeData(incomingRawAuthCodeValue);

    const validatedPayload = await this.validateAuthorizationCode(authCodeProperties, client, req);

    const userId = validatedPayload.user_id;

    const user = userId
      ? await this.userRepository.getUserByCredentials(userId, undefined, this.identifier, client)
      : undefined;

    const scopes: OAuthScope[] = [];

    try {
      const finalizedScopes = await this.scopeRepository.finalize(
        await this.validateScopes(validatedPayload.scopes ?? []),
        this.identifier,
        client,
        userId,
      );
      scopes.push(...finalizedScopes);
    } catch (_) {
      throw OAuthException.invalidParameter("code", "Cannot verify scopes");
    }

    const authCode =
      preloadedAuthCode ?? (await this.authCodeRepository.getByIdentifier(validatedPayload.auth_code_id));

    this.validateCodeChallenge(authCode, validatedPayload, req);

    const originatingAuthCodeId = validatedPayload.auth_code_id;
    let accessToken = await this.issueAccessToken(accessTokenTTL, client, user, scopes, originatingAuthCodeId);

    accessToken = await this.issueRefreshToken(accessToken, client);

    await this.authCodeRepository.revoke(validatedPayload.auth_code_id);

    const extraJwtFields = await this.extraJwtFields(req, client, user, accessToken.originatingAuthCodeId);

    return await this.makeBearerTokenResponse(client, accessToken, scopes, extraJwtFields);
  }

  /**
   * Enforces the PKCE code-challenge bound to the authorization code (RFC 7636).
   *
   * The challenge on the resolved payload is the enforcement authority: this
   * server mints and verifies it, while the persisted entity round-trips through
   * consumer storage that may drop the column and would otherwise silently
   * switch PKCE off for the whole deployment. The persisted copy is still
   * cross-checked whenever both carry one, and the challenge method is read from
   * whichever source supplied the challenge so a rewritten row cannot downgrade
   * S256 to plain.
   *
   * A code that carries no challenge in either source is refused outright when
   * the server requires PKCE; otherwise the check is a no-op.
   */
  private validateCodeChallenge(
    authCode: OAuthAuthCode,
    validatedPayload: PayloadAuthCode,
    req: RequestInterface,
  ): void {
    const signedChallenge = validatedPayload.code_challenge;
    const persistedChallenge = authCode?.codeChallenge;

    if (signedChallenge && persistedChallenge && !timingSafeCompare(signedChallenge, persistedChallenge)) {
      throw OAuthException.invalidGrant("Provided code challenge does not match auth code");
    }

    const codeChallenge = signedChallenge ?? persistedChallenge;

    if (!codeChallenge) {
      if (this.options.requiresPKCE) {
        throw OAuthException.invalidGrant(
          "The authorization server requires public clients to use PKCE RFC-7636, and this authorization code carries no code challenge",
        );
      }
      return;
    }

    const codeVerifier = this.getRequestParameter("code_verifier", req);

    if (!codeVerifier) {
      throw OAuthException.invalidParameter("code_verifier");
    }

    // Validate code_verifier according to RFC-7636
    // @see: https://tools.ietf.org/html/rfc7636#section-4.1
    if (!REGEXP_CODE_VERIFIER.test(codeVerifier)) {
      throw OAuthException.invalidParameter(
        "code_verifier",
        "Code verifier must follow the specifications of RFC-7636",
      );
    }

    const codeChallengeMethod: CodeChallengeMethod | undefined =
      (signedChallenge ? validatedPayload.code_challenge_method : authCode?.codeChallengeMethod) ?? undefined;

    let verifier: ICodeChallenge = this.codeChallengeVerifiers.plain;

    if (codeChallengeMethod === "S256") {
      verifier = this.codeChallengeVerifiers.S256;
    }

    if (!verifier.verifyCodeChallenge(codeVerifier, codeChallenge)) {
      throw OAuthException.invalidGrant("Failed to verify code challenge.");
    }
  }

  canRespondToAuthorizationRequest(request: RequestInterface): boolean {
    return this.getQueryStringParameter("response_type", request) === "code";
  }

  async validateAuthorizationRequest(request: RequestInterface): Promise<AuthorizationRequest> {
    const clientId = this.getQueryStringParameter("client_id", request);

    if (typeof clientId !== "string") {
      throw OAuthException.invalidParameter("client_id");
    }

    const client = await this.clientRepository.getByIdentifier(clientId);

    if (!client) {
      throw OAuthException.invalidClient();
    }

    const redirectUri = this.getRedirectUri(request, client);

    const bodyScopes = this.getQueryStringParameter("scope", request, []);

    const finalizedScopes = await this.scopeRepository.finalize(
      await this.validateScopes(bodyScopes),
      this.identifier,
      client,
    );

    const stateParameter = this.getQueryStringParameter("state", request);

    const audience: string[] | string | null | undefined =
      this.getQueryStringParameter("audience", request) ?? this.getQueryStringParameter("aud", request);

    const authorizationRequest = new AuthorizationRequest(this.identifier, client, redirectUri, undefined, audience);

    authorizationRequest.state = stateParameter;

    authorizationRequest.scopes = finalizedScopes;

    const codeChallenge = this.getQueryStringParameter("code_challenge", request);

    if (this.options.requiresPKCE && !codeChallenge) {
      throw OAuthException.invalidParameter(
        "code_challenge",
        "The authorization server requires public clients to use PKCE RFC-7636",
      );
    }

    if (codeChallenge) {
      const codeChallengeMethod: string = this.getQueryStringParameter("code_challenge_method", request, "plain");

      if (codeChallengeMethod !== "S256" && this.options.requiresS256) {
        throw OAuthException.invalidParameter("code_challenge_method", "Must be `S256`");
      }

      if (!(codeChallengeMethod === "S256" || codeChallengeMethod === "plain")) {
        throw OAuthException.invalidParameter("code_challenge_method", "Must be `S256` or `plain`");
      }

      authorizationRequest.codeChallenge = codeChallenge;
      authorizationRequest.codeChallengeMethod = codeChallengeMethod;
    }

    return authorizationRequest;
  }

  async completeAuthorizationRequest(authorizationRequest: AuthorizationRequest): Promise<ResponseInterface> {
    if (!authorizationRequest.user) {
      throw OAuthException.badRequest("A user should be set on the authorization request");
    }

    const redirectUri = authorizationRequest.redirectUri;

    if (!redirectUri) {
      throw OAuthException.invalidParameter("redirect_uri");
    }

    if (!authorizationRequest.isAuthorizationApproved) {
      throw OAuthException.badRequest("Authorization is not approved");
    }

    const authCode = await this.issueAuthCode(
      this.authCodeTTL,
      authorizationRequest.client,
      authorizationRequest.user.id,
      authorizationRequest.redirectUri,
      authorizationRequest.codeChallenge,
      authorizationRequest.codeChallengeMethod,
      authorizationRequest.scopes,
    );

    const code = await this.authCodeEncoder.issue(authCode, authorizationRequest, this.authCodeTTL.getEndTimeSeconds());

    const params: Record<string, string> = { code };

    if (authorizationRequest.state) params.state = authorizationRequest.state;

    const finalRedirectUri = this.makeRedirectUrl(redirectUri, params);

    return new RedirectResponse(finalRedirectUri);
  }

  private async validateAuthorizationCode(payload: any, client: OAuthClient, request: RequestInterface) {
    if (!payload.auth_code_id) {
      throw OAuthException.invalidParameter("code", "Authorization code malformed");
    }

    const isCodeRevoked = await this.authCodeRepository.isRevoked(payload.auth_code_id);

    // https://www.rfc-editor.org/rfc/rfc6749#section-4.1.2
    //   If an authorization code is used more than, the authorization server... SHOULD revoke (when possible) all
    //   tokens previously issued based on that authorization code.
    if (isCodeRevoked) {
      await this.tokenRepository.revokeDescendantsOf?.(payload.auth_code_id);
    }

    if (Date.now() / 1000 > payload.expire_time || isCodeRevoked) {
      throw OAuthException.invalidParameter("code", "Authorization code is expired or revoked");
    }

    if (payload.client_id !== client.id) {
      throw OAuthException.invalidParameter("code", "Authorization code was not issued to this client");
    }

    const redirectUri = this.getRequestParameter("redirect_uri", request);
    if (!!payload.redirect_uri && !redirectUri) {
      throw OAuthException.invalidParameter("redirect_uri");
    }

    if (payload.redirect_uri !== redirectUri) {
      throw OAuthException.invalidParameter("redirect_uri", "Invalid redirect URI");
    }
    return payload;
  }

  private async issueAuthCode(
    authCodeTTL: DateInterval,
    client: OAuthClient,
    userIdentifier?: OAuthUserIdentifier,
    redirectUri?: string,
    codeChallenge?: string,
    codeChallengeMethod?: CodeChallengeMethod,
    scopes: OAuthScope[] = [],
  ): Promise<OAuthAuthCode> {
    const user = userIdentifier
      ? await this.userRepository.getUserByCredentials(userIdentifier, undefined, this.identifier, client)
      : undefined;

    const authCode = await this.authCodeRepository.issueAuthCode(client, user, scopes);
    authCode.expiresAt = authCodeTTL.getEndDate();
    authCode.redirectUri = redirectUri;
    authCode.codeChallenge = codeChallenge;
    authCode.codeChallengeMethod = codeChallengeMethod;
    authCode.scopes = [];
    scopes.forEach(scope => authCode.scopes.push(scope));
    await this.authCodeRepository.persist(authCode);
    return authCode;
  }

  canRespondToRevokeRequest(request: RequestInterface): boolean {
    return this.getRequestParameter("token_type_hint", request) === "auth_code";
  }

  async respondToRevokeRequest(req: RequestInterface): Promise<ResponseInterface> {
    req.body["grant_type"] = this.identifier;

    // Silently ignore - per RFC 7009, invalid tokens should not cause error responses
    // @see https://datatracker.ietf.org/doc/html/rfc7009#section-2.2
    const errorResponse = new OAuthResponse();

    let authenticatedClient;
    if (this.options.authenticateRevoke) {
      try {
        authenticatedClient = await this.validateClient(req);
      } catch (err) {
        this.options.logger?.log(err);
        return errorResponse;
      }
    }

    const token = this.getRequestParameter("token", req);

    if (!token) {
      return errorResponse;
    }

    let providedAuthCode: string;
    let providedClientId: string;
    let isVerified: boolean;

    try {
      const { authCodeId, clientId, verified } = await this.getAuthCodeAndClient(token);
      providedAuthCode = authCodeId;
      providedClientId = clientId;
      isVerified = verified;
    } catch (err) {
      this.options.logger?.log(err);
      return errorResponse;
    }

    if (this.options.authenticateRevoke && authenticatedClient && providedAuthCode) {
      // An unverified payload proves nothing about ownership — anyone can mint
      // `{ auth_code_id: <victim>, client_id: <self> }` — so it can never
      // satisfy the ownership check.
      if (!isVerified) {
        this.options.logger?.log("Token signature could not be verified, refusing to establish token ownership");
        return errorResponse;
      }

      if (providedClientId !== authenticatedClient.id) {
        this.options.logger?.log("Token client ID does not match authenticated client");
        return errorResponse;
      }
    }

    try {
      await this.authCodeRepository.revoke(providedAuthCode);
    } catch (err) {
      this.options.logger?.log(err);
      // Silently ignore - per RFC 7009, invalid tokens should not cause error responses
    }

    return errorResponse;
  }

  private async resolveAuthCodeData(rawCode: string): Promise<{
    properties: PayloadAuthCode;
    authCode: OAuthAuthCode | null;
  }> {
    const { payload, authCode } = await this.authCodeEncoder.resolve(rawCode);
    return { properties: payload, authCode };
  }

  /**
   * Resolves the revoke endpoint's token, preferring the verified payload. RFC
   * 7009 asks the endpoint to accept tokens it can no longer verify (a rotated
   * signing key), so an unverified decode remains the fallback — flagged as
   * such, because its `client_id` is attacker-controlled and the caller must
   * not treat it as proof of ownership.
   */
  private async getAuthCodeAndClient(
    token: string,
  ): Promise<{ authCodeId: string; clientId: string; verified: boolean }> {
    try {
      const { payload } = await this.authCodeEncoder.resolve(token);
      return { authCodeId: payload.auth_code_id, clientId: payload.client_id, verified: true };
    } catch (err) {
      this.options.logger?.log(err);
    }

    const { auth_code_id, client_id } = await this.authCodeEncoder.unverifiedDecode(token);
    return { authCodeId: auth_code_id, clientId: client_id, verified: false };
  }
}
