import 'dart:convert';
import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:frontend_eccp_mobile/app/core/utils/session_manager.dart';

class AuthInterceptor extends Interceptor {
  @override
  Future<void> onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) async {
    final noAuth = options.extra['noAuth'] == true;

    if (!noAuth) {
      final token = await SessionManager.getToken();

      if (token != null && token.isNotEmpty) {
        options.headers['Authorization'] = 'Bearer $token';
      } else {
        options.headers.remove('Authorization');
      }
    }

    if (options.data is Map || options.data is List) {
      options.headers.putIfAbsent(
        'Content-Type',
        () => 'application/json',
      );
    }

    if (!kReleaseMode) {
      final curl = StringBuffer()
        ..write("curl -X ${options.method} '${options.uri}'");

      options.headers.forEach((k, v) {
        curl.write(" -H '$k: $v'");
      });

      if (options.data != null) {
        if (options.data is FormData) {
          final formData = options.data as FormData;

          for (final field in formData.fields) {
            curl.write(" -F '${field.key}=${field.value}'");
          }

          for (final file in formData.files) {
            curl.write(
              " -F '${file.key}=@${file.value.filename ?? 'file'}'",
            );
          }
        } else {
          curl.write(
            " -d '${jsonEncode(options.data)}'",
          );
        }
      }

      log(
        curl.toString(),
        name: 'DIO_CURL',
      );
    }

    handler.next(options);
  }
}
