import 'package:dio/dio.dart';

import '../../../../core/error/custom_error.dart';
import '../../../../core/resources/data_state.dart';
import '../../../../core/usecase/use_case.dart';
import '../../domain/entities/user_entity.dart';
import '../../domain/repository/auth_repository.dart';
import '../data_source/local/auth_local_data.dart';
import '../data_source/remote/auth_api_provider.dart';
import '../model/user_model.dart';

class AuthRepositoryImpl extends AuthRepository {
  final AuthApiProvider api;
  final AuthLocalData local;
  AuthRepositoryImpl(this.api, this.local);

  @override
  Future<DataState<String>> loginOtp(String mobile) async {
    final Response res = await api.loginOtp(mobile);
    if (res.statusCode == 200) {
      return const DataSuccess('ok');
    }
    return DataError(errorConvertor(res.statusCode, _msg(res)));
  }

  @override
  Future<DataState<UserEntity>> checkOtp(OtpParams params) async {
    final Response res = await api.checkOtp(params.mobile, params.token);
    if (res.statusCode == 200) {
      final token = res.data['token'] as String?;
      if (token == null || token.isEmpty) {
        return const DataError('پاسخ نامعتبر از سرور');
      }
      await local.saveToken(token);
      await local.saveMobile(params.mobile); // برای payloadِ خریدِ فروشگاهی
      return DataSuccess(UserModel.fromJson(
          Map<String, dynamic>.from(res.data['user'] as Map)));
    }
    return DataError(errorConvertor(res.statusCode, _msg(res)));
  }

  @override
  Future<DataState<UserEntity>> updateProfile(ProfileParams params) async {
    final Response res = await api.updateProfile(params.firstName, params.avatar);
    if (res.statusCode == 200) {
      return DataSuccess(UserModel.fromJson(
          Map<String, dynamic>.from(res.data['user'] as Map)));
    }
    return DataError(errorConvertor(res.statusCode, _msg(res)));
  }

  @override
  Future<DataState<String>> logout() async {
    await local.clearToken();
    return const DataSuccess('ok');
  }

  @override
  Future<bool> isLoggedIn() => local.hasToken();

  String? _msg(Response res) {
    final d = res.data;
    if (d is Map && d['message'] != null) return d['message'].toString();
    return null;
  }
}
