import { normalizeNullableStringId, normalizeStringId } from './shared';

type ProductStatusCode = Api.Product.ProductStatusCode;
type ProductStatusActionCode = Api.Product.ProductStatusActionCode;

interface ProductSettingsResponse {
  baseInfo: {
    id: string | number;
    code: string;
    directionCode: string;
    name: string;
    managerUserId?: string | number | null;
    managerUserNickname?: string | null;
    description?: string | null;
    statusCode: ProductStatusCode;
    lastStatusReason?: string | null;
  };
  lifecycle: {
    statusCode: ProductStatusCode;
    lastStatusReason?: string | null;
    availableActions?: Array<{
      actionCode: ProductStatusActionCode;
      actionName: string;
      needReason: boolean;
    }> | null;
  };
}

interface ProductMemberResponse {
  id: string | number;
  userId: string | number;
  userNickname: string;
  roleId: string | number;
  roleName: string;
  roleCode: string;
  managerFlag: boolean;
  status: 0 | 1;
  joinedTime: string;
  leftTime?: string | null;
  remark?: string | null;
}

export function normalizeProductSettings(response: ProductSettingsResponse): Api.Product.ProductSettings {
  return {
    baseInfo: {
      id: normalizeStringId(response.baseInfo.id),
      code: response.baseInfo.code || '',
      directionCode: response.baseInfo.directionCode || '',
      name: response.baseInfo.name || '',
      managerUserId: normalizeNullableStringId(response.baseInfo.managerUserId) ?? '',
      managerUserNickname: response.baseInfo.managerUserNickname || '',
      description: response.baseInfo.description ?? null,
      statusCode: response.baseInfo.statusCode,
      lastStatusReason: response.baseInfo.lastStatusReason ?? null
    },
    lifecycle: {
      statusCode: response.lifecycle.statusCode,
      lastStatusReason: response.lifecycle.lastStatusReason ?? null,
      availableActions:
        response.lifecycle.availableActions?.map(item => ({
          actionCode: item.actionCode,
          actionName: item.actionName,
          needReason: item.needReason
        })) ?? []
    }
  };
}

export function normalizeProductMember(response: ProductMemberResponse): Api.Product.ProductMember {
  return {
    id: normalizeStringId(response.id),
    userId: normalizeStringId(response.userId),
    userNickname: response.userNickname || '',
    roleId: normalizeStringId(response.roleId),
    roleName: response.roleName || '',
    roleCode: response.roleCode || '',
    managerFlag: Boolean(response.managerFlag),
    status: response.status,
    joinedTime: response.joinedTime,
    leftTime: response.leftTime ?? null,
    remark: response.remark ?? null
  };
}
