import 'dart:developer';
import 'package:dartz/dartz.dart';
import 'package:dio/dio.dart';
import 'package:enaklo_pos/core/network/dio_client.dart';
import 'package:enaklo_pos/data/datasources/outlet/outlet_local_datasource.dart';
import 'package:enaklo_pos/data/datasources/settings_local_datasource.dart';
import 'package:enaklo_pos/presentation/home/models/outlet_model.dart';
import 'package:enaklo_pos/presentation/setting/models/tax_model.dart';
import '../../../core/constants/variables.dart';
import '../auth_local_datasource.dart';

class OutletRemoteDataSource {
  final Dio dio = DioClient.instance;

  Future<Either<String, OutletResponse>> getOutlets() async {
    try {
      final authData = await AuthLocalDataSource().getAuthData();

      final url = '${Variables.baseUrl}/api/v1/outlets/list';

      final response = await dio.get(
        url,
        queryParameters: {
          'organization_id': authData.user?.organizationId,
        },
        options: Options(
          headers: {
            'Authorization': 'Bearer ${authData.token}',
            'Accept': 'application/json',
          },
        ),
      );

      if (response.statusCode == 200) {
        final data = OutletResponse.fromMap(response.data);
        return Right(data);
      } else {
        return const Left('Failed to get outlets');
      }
    } on DioException catch (e) {
      log("Dio error: ${e.message}");
      return Left(e.response?.data['message'] ?? 'Gagal mengambil outlet');
    } catch (e) {
      log("Unexpected error: $e");
      return const Left('Unexpected error occurred');
    }
  }

  Future<Either<String, OutletDetailResponse>> currentOutlet() async {
    try {
      final authData = await AuthLocalDataSource().getAuthData();

      if (authData.user?.outletId == null) {
        return const Left('Kamu belum memiliki bergabung dengan outlet');
      }

      final url =
          '${Variables.baseUrl}/api/v1/outlets/detail/${authData.user?.outletId}';

      final response = await dio.get(
        url,
        queryParameters: {
          'organization_id': authData.user?.organizationId,
        },
        options: Options(
          headers: {
            'Authorization': 'Bearer ${authData.token}',
            'Accept': 'application/json',
          },
        ),
      );

      if (response.statusCode == 200) {
        final data = OutletDetailResponse.fromMap(response.data);
        await SettingsLocalDatasource().saveTax(
          TaxModel(
            name: 'PB1',
            type: TaxType.pajak,
            value: data.data?.taxRate ?? 0,
          ),
        );

        await OutletLocalDatasource().save(data.data!);
        return Right(data);
      } else {
        return const Left('Failed to get outlets');
      }
    } on DioException catch (e) {
      log("Dio error: ${e.message}");
      return Left(e.response?.data['message'] ?? 'Gagal mengambil outlet');
    } catch (e) {
      log("Unexpected error: $e");
      return const Left('Unexpected error occurred');
    }
  }
}
