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/category_response_model.dart';

class CategoryRemoteDatasource {
  final Dio dio = DioClient.instance;

  Future<Either<String, CategoryResponseModel>> getCategories({
    int page = 1,
    int limit = 10,
    bool isActive = true,
  }) async {
    final authData = await AuthLocalDataSource().getAuthData();
    final headers = {
      'Authorization': 'Bearer ${authData.token}',
      'Accept': 'application/json',
    };

    try {
      final response = await dio.get(
        '${Variables.baseUrl}/api/v1/categories',
        queryParameters: {
          'page': page,
          'limit': limit,
          'is_active': isActive,
        },
        options: Options(headers: headers),
      );

      if (response.statusCode == 200) {
        return right(CategoryResponseModel.fromMap(response.data));
      } else {
        return left(response.data.toString());
      }
    } on DioException catch (e) {
      log('Dio error: ${e.message}');
      return left(e.response?.data.toString() ?? e.message ?? 'Unknown error');
    } catch (e) {
      log('Unexpected error: $e');
      return left('Unexpected error occurred');
    }
  }
}
