import 'dart:convert';
import 'package:syncrow_web/pages/access_management/model/password_model.dart';
import 'package:syncrow_web/pages/visitor_password/model/device_model.dart';
import 'package:syncrow_web/pages/visitor_password/model/schedule_model.dart';
import 'package:syncrow_web/services/api/http_service.dart';
import 'package:syncrow_web/utils/constants/api_const.dart';

class AccessMangApi {
  AccessMangApi() {
    _validateEndpoints();
  }

  void _validateEndpoints() {
    if (!ApiEndpoints.getDevices.contains('{projectId}')) {
      throw Exception("Endpoint 'getDevices' must contain '{projectId}' placeholder.");
    }
  }

  Future<List<PasswordModel>> fetchVisitorPassword(String projectId) async {
    try {
      final response = await HTTPService().get(
        path: ApiEndpoints.visitorPassword,
        showServerMessage: true,
        expectedResponseModel: (json) {
          List<dynamic> jsonData = json['data'] ?? [];
          List<PasswordModel> passwordList = jsonData.map((jsonItem) {
            return PasswordModel.fromJson(jsonItem);
          }).toList();
          return passwordList;
        },
      );
      return response;
    } catch (e) {
      return [];
    }
  }

  Future fetchDoorLockDeviceList(String projectId) async {
    try {
      // The endpoint structure is already validated during initialization.

      final response = await HTTPService().get(
        path: ApiEndpoints.getDevices.replaceAll('{projectId}', projectId),
        queryParameters: {
          'deviceType': 'DOOR_LOCK',
        },
        showServerMessage: true,
        expectedResponseModel: (json) {
          List<dynamic> jsonData = json['data'] ?? [];
          List<DeviceModel> deviceList = jsonData.map((jsonItem) {
            return DeviceModel.fromJson(jsonItem);
          }).toList();
          return deviceList;
        },
      );
      return response;
    } catch (e) {
      return [];
    }
  }

  Future postOnlineOneTime(
      {String? email,
      String? passwordName,
      String? password,
      String? effectiveTime,
      String? invalidTime,
      List<String>? devicesUuid}) async {
    final response = await HTTPService().post(
      path: ApiEndpoints.visitorPassword,
      body: jsonEncode({
        "email": email,
        "passwordName": passwordName,
        "password": password,
        "devicesUuid": devicesUuid,
        "effectiveTime": effectiveTime,
        "invalidTime": invalidTime,
        "operationType": "ONLINE_ONE_TIME",
      }),
      showServerMessage: true,
      expectedResponseModel: (json) {
        return json;
      },
    );
    return response;
  }

  Future postOnlineMultipleTime(
      {String? effectiveTime,
      String? invalidTime,
      String? email,
      String? password,
      String? passwordName,
      List<Schedule>? scheduleList,
      List<String>? devicesUuid}) async {
    Map<String, dynamic> body = {
      "email": email,
      "devicesUuid": devicesUuid,
      "passwordName": passwordName,
      "password": password,
      "effectiveTime": effectiveTime,
      "invalidTime": invalidTime,
      "operationType": "ONLINE_MULTIPLE_TIME",
    };
    if (scheduleList != null) {
      body["scheduleList"] = scheduleList.map((schedule) => schedule.toJson()).toList();
    }
    final response = await HTTPService().post(
      path: ApiEndpoints.visitorPassword,
      body: jsonEncode(body),
      showServerMessage: true,
      expectedResponseModel: (json) {
        return json;
      },
    );
    return response;
  }

// OffLine One Time Password

  Future postOffLineOneTime(
      {String? email, String? passwordName, List<String>? devicesUuid}) async {
    final response = await HTTPService().post(
      path: ApiEndpoints.visitorPassword,
      body: jsonEncode({
        "operationType": "OFFLINE_ONE_TIME",
        "email": email,
        "passwordName": passwordName,
        "devicesUuid": devicesUuid
      }),
      showServerMessage: true,
      expectedResponseModel: (json) {
        return json;
      },
    );
    return response;
  }

  Future postOffLineMultipleTime(
      {String? email,
      String? passwordName,
      String? effectiveTime,
      String? invalidTime,
      List<String>? devicesUuid}) async {
    final response = await HTTPService().post(
      path: ApiEndpoints.visitorPassword,
      body: jsonEncode({
        "email": email,
        "devicesUuid": devicesUuid,
        "passwordName": passwordName,
        "effectiveTime": effectiveTime,
        "invalidTime": invalidTime,
        "operationType": "OFFLINE_MULTIPLE_TIME",
      }),
      showServerMessage: true,
      expectedResponseModel: (json) {
        return json;
      },
    );
    return response;
  }
}
