import { AppType, DeviceType } from '@ucap-webmessenger/core';
import {
  APIRequest,
  APIResponse,
  APIEncoder,
  APIDecoder,
  ParameterUtil
} from '@ucap-webmessenger/api';
import { Company } from '../models/company';

export interface CompanyListRequest extends APIRequest {
  userSeq?: number;
  appType?: AppType;
  deviceType?: DeviceType;
  token?: string;
  companyGroupCode: string;
}

export interface CompanyListResponse extends APIResponse {
  companyList?: Company[];
}

const companyListEncodeMap = {
  userSeq: 'p_user_seq',
  appType: 'p_app_type',
  deviceType: 'p_device_type',
  token: 'p_token',
  companyGroupCode: 'p_comp_group_code'
};

export const encodeCompanyList: APIEncoder<CompanyListRequest> = (
  req: CompanyListRequest
) => {
  const extraParams: any = {};

  extraParams.userSeq = String(req.userSeq);

  return ParameterUtil.encode(companyListEncodeMap, req, extraParams);
};

export const decodeCompanyList: APIDecoder<CompanyListResponse> = (
  res: any
) => {
  let companyList: Company[] | undefined;
  if (!!res.CompanyList) {
    companyList = [];
    for (const company of res.CompanyList) {
      companyList.push({
        companyCode: company.COMPANY_CODE,
        companyName: company.COMPANY_NAME,
        companyDomain: company.COMPANY_DOMAIN,
        companyConfAuthYn: company.COMPANY_CONF_AUTH,
        ucapUseYn: company.UCAP_USE_YN,
        companyTimerChatAuthYn: company.COMPANY_TIMER_CHAT_AUTH
      });
    }
  }

  return {
    statusCode: res.StatusCode,
    errorMessage: res.ErrorMessage,
    companyList
  } as CompanyListResponse;
};
