import { code } from 'dashboard/generated/controlplane';
import { createServices } from 'dashboard/generated/controlplane/twirp';
import * as _ from 'lodash';
import { TwirpHTTPError } from 'pbjs-twirp';
import { useEffect, useState } from 'react';
import { GetControlplaneEndpoint } from './env';

import twirp = code.justin.tv.eventbus.controlplane;

export const useAuthorizedFieldGrants = (serviceId: string) => {
  const client = createServices(GetControlplaneEndpoint());

  const [publisherGrants, setPublisherGrants] = useState<
    twirp.IAuthorizedFieldPublisherGrant[]
  >(new Array<twirp.AuthorizedFieldPublisherGrant>());
  const [subscriberGrants, setSubscriberGrants] = useState<
    twirp.IAuthorizedFieldPublisherGrant[]
  >(new Array<twirp.AuthorizedFieldPublisherGrant>());

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [forbidden, setForbidden] = useState(false);
  const [reloadToggle, setReloadToggle] = useState(false);

  const reload = () => {
    setReloadToggle(!reloadToggle);
  };

  const getAuthFieldGrantsReq = new twirp.GetAuthorizedFieldGrantsReq({
    serviceId,
  });

  useEffect(() => {
    if (_.isNil(serviceId) || serviceId === '') {
      return;
    }
    const fetchData = async () => {
      try {
        const resp = await client.getAuthorizedFieldGrants(
          getAuthFieldGrantsReq,
        );
        setPublisherGrants(resp.publisherGrants);
        setSubscriberGrants(resp.subscriberGrants);
        setLoading(false);
      } catch (err) {
        if (
          err instanceof TwirpHTTPError &&
          (err as TwirpHTTPError).status === 403
        ) {
          setForbidden(true);
          setLoading(false);
        } else {
          setLoading(false);
          setError(err);
        }
      }
    };
    fetchData();
  }, [serviceId, reloadToggle]);

  return {
    publisherGrants,
    subscriberGrants,
    loading,
    error,
    forbidden,
    reload,
  };
};
