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 UserRemoteDatasource {
  final Dio dio = DioClient.instance;

  Future<Either<String, bool>> updateOutlet(String outletId) async {
    AuthResponseModel authData = await AuthLocalDataSource().getAuthData();
    final url = '${Variables.baseUrl}/api/v1/users/${authData.user?.id}';

    try {
      final response = await dio.put(
        url,
        data: {
          'outlet_id': outletId,
        },
        options: Options(
          headers: {
            'Authorization': 'Bearer ${authData.token}',
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
        ),
      );

      if (response.statusCode == 200) {
        authData.user?.outletId = response.data['outlet_id'];
        await AuthLocalDataSource().saveAuthData(authData);
        return Right(true);
      } 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');
    }
  }
}
