// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// 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, either version 3 of the License, or
// any later version.
//
// 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 'dart:convert';

import 'package:wyatt_http_client/src/middleware.dart';
import 'package:wyatt_http_client/src/middleware_client.dart';
import 'package:wyatt_http_client/src/models/middleware_context.dart';
import 'package:wyatt_http_client/src/models/middleware_request.dart';
import 'package:wyatt_http_client/src/models/middleware_response.dart';
import 'package:wyatt_http_client/src/utils/authentication_methods.dart';
import 'package:wyatt_http_client/src/utils/delay.dart';
import 'package:wyatt_http_client/src/utils/header_keys.dart';
import 'package:wyatt_http_client/src/utils/http_status.dart';

typedef TokenParser = String Function(Map<String, dynamic>);

class RefreshTokenAuthMiddleware
    with OnRequestMiddleware, OnResponseMiddleware
    implements Middleware {

  RefreshTokenAuthMiddleware({
    required this.authorizationEndpoint,
    required this.tokenEndpoint,
    required this.accessTokenParser,
    required this.refreshTokenParser,
    this.authenticationHeader = HeaderKeys.authorization,
    this.authenticationMethod = AuthenticationMethods.bearer,
    this.unauthorized = HttpStatus.unauthorized,
    this.maxAttempts = 8,
  });
  final String authorizationEndpoint;
  final String tokenEndpoint;

  String? accessToken;
  final TokenParser accessTokenParser;
  String? refreshToken;
  final TokenParser refreshTokenParser;

  final String authenticationHeader;
  final String authenticationMethod;
  final HttpStatus unauthorized;
  final int maxAttempts;

  @override
  String getName() => 'RefreshToken';

  Future<MiddlewareRequest?> refresh(MiddlewareContext context) async {
    final subPipeline = context.pipeline.sub(this);
    final httpClient = MiddlewareClient(
      pipeline: subPipeline,
      inner: context.client.inner,
    );
    final headers = {
      authenticationHeader: '$authenticationMethod $refreshToken',
    };
    final response = MiddlewareResponse(
      httpResponse: await httpClient.get(
        Uri.parse(tokenEndpoint),
        headers: headers,
      ),
    );
    if (response.status.isSuccess()) {
      final body = jsonDecode(response.body) as Map<String, dynamic>;
      accessToken = accessTokenParser(body);

      // Then modify current request with accessToken
      final mutation = {
        authenticationHeader: '$authenticationMethod $accessToken',
      };
      final Map<String, String>? headers = context.lastRequest?.headers
        ?..addAll(mutation);
      final newRequest = context.lastRequest?.copyWith(
        unfreezedRequest:
            context.lastRequest?.unfreezedRequest.copyWith(headers: headers),
      );

      return newRequest;
    }
    return null;
  }

  Future<MiddlewareRequest?> retry(MiddlewareContext context) async {
    // Retry
    int attempt = 1;
    while (attempt <= maxAttempts) {
      // Delayed before retry
      await Future<void>.delayed(Delay.getRetryDelay(attempt));

      final newRequest = await refresh(context);
      if (newRequest != null) {
        return newRequest;
      }
      attempt++;
    }
    return null;
  }

  @override
  Future<MiddlewareRequest> onRequest(
    MiddlewareContext context,
    MiddlewareRequest request,
  ) async {
    print(
      '${getName()}::OnRequest\n'
      '>> accessToken: $accessToken\n'
      '>> refreshToken: $refreshToken',
    );
    // Check if it is authorization
    if (context.originalRequest?.url == Uri.parse(authorizationEndpoint)) {
      return request;
    }
    // Check if it is refresh
    if (context.originalRequest?.url == Uri.parse(tokenEndpoint)) {
      return request;
    }
    // If AccessToken not null then return request with authorization header
    if (accessToken != null) {
      final mutation = {
        authenticationHeader: '$authenticationMethod $accessToken',
      };
      final Map<String, String> headers = request.headers..addAll(mutation);
      request
          .modifyRequest(request.unfreezedRequest.copyWith(headers: headers));
      return request;
    }
    // If AccessToken is null BUT there is a refreshToken, then try refreshing
    if (refreshToken != null) {
      MiddlewareRequest? newRequest = await refresh(context);
      newRequest ??= await retry(context);
      return newRequest ?? request;
    }
    // Pass
    return request;
  }

  @override
  Future<MiddlewareResponse> onResponse(
    MiddlewareContext context,
    MiddlewareResponse response,
  ) async {
    // Check if it is authorization
    if (context.originalRequest?.url == Uri.parse(authorizationEndpoint)) {
      // If success, then update tokens
      if (response.status.isSuccess()) {
        final body = jsonDecode(response.body) as Map<String, dynamic>;
        final accessToken = accessTokenParser(body);
        final refreshToken = refreshTokenParser(body);

        if (accessToken.isNotEmpty) {
          this.accessToken = accessToken;
        }
        if (refreshToken.isNotEmpty) {
          this.refreshToken = refreshToken;
        }
      }
    }

    print(
      '${getName()}::OnResponse\n'
      '>> accessToken: $accessToken\n'
      '>> refreshToken: $refreshToken',
    );

    if (response.status == unauthorized) {
      // Refresh
      MiddlewareRequest? newRequest = await refresh(context);
      newRequest ??= await retry(context);

      if (newRequest != null) {
        return response.copyWith(
          httpResponse: await context.client.send(newRequest.request),
        );
      }
    }
    return response;
  }
}
