import { API_READER } from '@/constants/api';
import { request } from '@umijs/max';

// Transform functions
function transformEntityConfigChildDetail(
  raw: MasterModel.PurpleC,
): MasterModel.EntityConfigChildDetail {
  return {
    entityId: raw.eid || '',
    value: raw.v,
    operation: raw.op,
    duration: raw.for,
  };
}

function transformEntityConfigChild(
  raw: MasterModel.CElement,
): MasterModel.EntityConfigChild {
  return {
    type: raw.t || '',
    children: raw.c ? [transformEntityConfigChildDetail(raw.c)] : undefined,
  };
}

function transformEntityConfig(raw: MasterModel.EC): MasterModel.EntityConfig {
  return {
    level: raw.l as 0 | 1 | 2 | undefined,
    normalCondition: raw.nc,
    subType: raw.st,
    children: raw.c?.map(transformEntityConfigChild),
  };
}

function transformEntity(raw: MasterModel.E): MasterModel.Entity {
  return {
    entityId: raw.eid || '',
    type: raw.t || '',
    name: raw.n || '',
    active: raw.a,
    value: raw.v,
    config: raw.c ? [transformEntityConfig(raw.c)] : undefined,
  };
}

export function transformNodeConfig(
  raw: MasterModel.RawNodeConfig,
): MasterModel.NodeConfig {
  return {
    nodeId: raw.nid || '',
    type: raw.t || '',
    name: raw.n || '',
    entities: raw.e?.map(transformEntity) || [],
  };
}

// Reverse transform functions
function reverseTransformEntityConfigChildDetail(
  detail: MasterModel.EntityConfigChildDetail,
): MasterModel.PurpleC {
  return {
    eid: detail.entityId,
    v: detail.value,
    op: detail.operation,
    for: detail.duration,
  };
}

function reverseTransformEntityConfigChild(
  child: MasterModel.EntityConfigChild,
): MasterModel.CElement {
  return {
    t: child.type,
    c: child.children?.[0]
      ? reverseTransformEntityConfigChildDetail(child.children[0])
      : undefined,
  };
}

function reverseTransformEntityConfig(
  raw: MasterModel.EntityConfig,
): MasterModel.EC {
  return {
    l: raw.level,
    nc: raw.normalCondition,
    st: raw.subType,
    c: raw.children?.map(reverseTransformEntityConfigChild),
  };
}

function reverseTransformEntity(entity: MasterModel.Entity): MasterModel.E {
  return {
    eid: entity.entityId,
    t: entity.type,
    n: entity.name,
    a: entity.active,
    v: entity.value,
    c: entity.config?.[0]
      ? reverseTransformEntityConfig(entity.config[0])
      : undefined,
  };
}

export function transformRawNodeConfig(
  node: MasterModel.NodeConfig,
): MasterModel.RawNodeConfig {
  return {
    nid: node.nodeId,
    t: node.type,
    n: node.name,
    e: node.entities.map(reverseTransformEntity),
  };
}

export async function apiQueryNodeConfigMessage(
  dataChanelId: string,
  authorization: string,
  params: MasterModel.SearchMessagePaginationBody,
) {
  const resp = await request<
    MasterModel.MesageReaderResponse<MasterModel.NodeConfig[]>
  >(`${API_READER}/${dataChanelId}/messages`, {
    method: 'GET',
    headers: {
      Authorization: authorization,
    },
    params: params,
  });

  // Process messages to add string_value_parsed
  if (resp.messages) {
    resp.messages = resp.messages.map((message) => {
      if (message.string_value) {
        try {
          const rawNodeConfigs: MasterModel.RawNodeConfig[] = JSON.parse(
            message.string_value,
          );
          message.string_value_parsed = rawNodeConfigs.map(transformNodeConfig);
        } catch (error) {
          console.error('Failed to parse string_value:', error);
        }
      }
      return message;
    });
  }

  return resp;
}

export async function apiQueryCamera(
  dataChanelId: string,
  authorization: string,
  params: MasterModel.SearchMessagePaginationBody,
) {
  const resp = await request<MasterModel.CameraV6MessageResponse>(
    `${API_READER}/${dataChanelId}/messages`,
    {
      method: 'GET',
      headers: {
        Authorization: authorization,
      },
      params: params,
    },
  );

  // Process messages to add string_value_parsed
  if (resp.messages) {
    resp.messages = resp.messages.map((message) => {
      if (message.string_value) {
        try {
          message.string_value_parsed = JSON.parse(message.string_value);
        } catch (error) {
          console.error('Failed to parse string_value:', error);
        }
      }
      return message;
    });
  }

  return resp;
}

export async function apiQueryConfigAlarm(
  dataChanelId: string,
  authorization: string,
  params: MasterModel.SearchMessagePaginationBody,
) {
  const resp = await request<MasterModel.AlarmMessageResponse>(
    `${API_READER}/${dataChanelId}/messages`,
    {
      method: 'GET',
      headers: {
        Authorization: authorization,
      },
      params: params,
    },
  );

  // Process messages to add string_value_parsed
  if (resp.messages) {
    resp.messages = resp.messages.map((message) => {
      if (message.string_value) {
        try {
          message.string_value_parsed = JSON.parse(message.string_value);
        } catch (error) {
          console.error('Failed to parse string_value:', error);
        }
      }
      return message;
    });
  }

  return resp;
}

export async function apiQuerySensorLogMessage(
  dataChanelId: string,
  authorization: string,
  params: MasterModel.SearchMessagePaginationBody,
) {
  return request<
    MasterModel.MesageReaderResponse<MasterModel.SensorLogMessage[]>
  >(`${API_READER}/${dataChanelId}/messages`, {
    method: 'GET',
    headers: {
      Authorization: authorization,
    },
    params: params,
  });
}
