import {
  API_THING,
  API_THING_POLICY,
  API_THINGS_SEARCH,
} from '@/constants/api';
import { request } from '@umijs/max';

export async function apiSearchThings(
  body: MasterModel.SearchPaginationBody,
  domain: 'spole',
): Promise<SpoleModel.SpoleThingsResponse>;
export async function apiSearchThings(
  body: MasterModel.SearchPaginationBody,
  domain: 'sgw',
): Promise<SgwModel.SgwThingsResponse>;
export async function apiSearchThings(
  body: MasterModel.SearchPaginationBody,
  domain?: 'gms',
): Promise<GmsModel.GmsThingsResponse>;
export async function apiSearchThings(
  body: MasterModel.SearchPaginationBody,
  domain?: string,
): Promise<
  | SpoleModel.SpoleThingsResponse
  | SgwModel.SgwThingsResponse
  | GmsModel.GmsThingsResponse
>;
export async function apiSearchThings(
  body: MasterModel.SearchPaginationBody,
  domain: string = process.env.DOMAIN_ENV || 'gms',
) {
  switch (domain) {
    case 'sgw':
      return request<SgwModel.SgwThingsResponse>(API_THINGS_SEARCH, {
        method: 'POST',
        data: body,
      });
    case 'gms':
      return request<GmsModel.GmsThingsResponse>(API_THINGS_SEARCH, {
        method: 'POST',
        data: body,
      });
    case 'spole':
      return request<SpoleModel.SpoleThingsResponse>(API_THINGS_SEARCH, {
        method: 'POST',
        data: body,
      });
    default:
      return request<GmsModel.GmsThingsResponse>(API_THINGS_SEARCH, {
        method: 'POST',
        data: body,
      });
  }
}

export async function apiUpdateThing(value: MasterModel.Thing) {
  if (!value.id) throw new Error('Thing id is required');
  return request<MasterModel.Thing>(`${API_THING}/${value.id}`, {
    method: 'PUT',
    data: value,
  });
}

export async function apiGetThingPolicyByUser(
  params: Partial<MasterModel.SearchPaginationBody>,
  userId: string,
) {
  return request<MasterModel.ThingPolicyResponse>(
    `${API_THING_POLICY}/${userId}`,
    {
      params: params,
    },
  );
}

export async function apiDeleteUserThingPolicy(
  thing_id: string,
  user_id: string,
) {
  return request(`${API_THING}/${thing_id}/share`, {
    method: 'DELETE',
    data: {
      policies: ['read', 'write', 'delete'],
      user_ids: [user_id],
    },
    getResponse: true,
  });
}
export async function apiShareThingToUser(
  thing_id: string,
  user_id: string,
  policies: string[],
) {
  return request(`${API_THING}/${thing_id}/share`, {
    method: 'POST',
    data: {
      policies: policies,
      user_ids: [user_id],
    },
    getResponse: true,
  });
}

export async function apiGetThingDetail(thing_id: string) {
  return request<MasterModel.Thing>(`${API_THING}/${thing_id}`);
}
