import 'dart:developer';

import 'package:dartz/dartz.dart';
import 'package:dio/dio.dart';
import 'package:enaklo_pos/core/constants/variables.dart';
import 'package:enaklo_pos/core/network/dio_client.dart';
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
import 'package:enaklo_pos/data/models/response/auth_response_model.dart';

class AuthRemoteDatasource {
  final Dio dio = DioClient.instance;
  Future<Either<String, AuthResponseModel>> login(
      String email, String password) async {
    final url = '${Variables.baseUrl}/api/v1/auth/login';
    log(url);

    try {
      final response = await dio.post(
        url,
        data: {
          'email': email,
          'password': password,
        },
      );

      if (response.statusCode == 200) {
        return Right(AuthResponseModel.fromMap(response.data['data']));
      } else {
        return const Left('Failed to login');
      }
    } on DioException catch (e) {
      log("Dio error: ${e.message}");
      return Left(e.response?.data['message'] ?? 'Login gagal');
    } catch (e) {
      log("Unexpected error: $e");
      return const Left('Unexpected error occurred');
    }
  }

  //logout
  Future<Either<String, bool>> logout() async {
    try {
      final authData = await AuthLocalDataSource().getAuthData();
      final url = '${Variables.baseUrl}/api/v1/auth/logout';

      final response = await dio.post(
        url,
        options: Options(
          headers: {
            'Authorization': 'Bearer ${authData.token}',
            'Accept': 'application/json',
          },
        ),
      );

      if (response.statusCode == 200) {
        return const Right(true);
      } else {
        return const Left('Failed to logout');
      }
    } on DioException catch (e) {
      return Left(e.response?.data['message'] ?? 'Logout gagal');
    } catch (e) {
      return const Left('Unexpected error occurred');
    }
  }
}
