export default function useSite() {
  const sites = ref<Array<TSite>>([]);
  const page = ref(1);
  const pages = ref(0);
  const pageRange = ref("-- - -- of --");
  const search = ref("");

  const site = useState(
    "site",
    (): TSite => ({
      _id: "",
      name: "",
      description: "",
      orgId: "",
      blocks: 0,
      customerOrgId: "",
      customerSiteId: "",
      createdAt: "",
      updatedAt: "",
      deletedAt: "",
    })
  );

  const { currentUser } = useLocalAuth();

  async function getSites({
    orgId,
    page: requestPage = 1,
    search: searchQuery = "",
    limit = 10,
    sort = "createdAt",
    order = "asc",
  }: {
    orgId?: string;
    page?: number;
    search?: string;
    limit?: number;
    sort?: string;
    order?: string;
  } = {}) {
    try {
      const organizationId = orgId || currentUser.value?.defaultOrg;

      const response = await useNuxtApp().$api<Record<string, any>>(
        `/api/sites/organization/${organizationId}`,
        {
          method: "GET",
          query: { page: requestPage, search: searchQuery, limit, sort, order },
        }
      );

      sites.value = response.items;
      page.value = requestPage;
      pages.value = response.pages;
      pageRange.value = response.pageRange;

      return response;
    } catch (err) {
      console.error(err);
    }
  }

  function createSite(payload: TSiteCreate) {
    return useNuxtApp().$api<Record<string, any>>(`/api/sites`, {
      method: "POST",
      body: payload,
    });
  }

  function deleteSite(id: string) {
    return useNuxtApp().$api<Record<string, any>>(`/api/sites/${id}`, {
      method: "DELETE",
    });
  }

  async function getSiteById(id: string) {
    return useNuxtApp().$api<TSite>(`/api/sites/${id}`, {
      method: "GET",
    });
  }

  function getAll({
    org = "",
    page = 1,
    search = "",
    limit = 10,
    sort = "createdAt",
    order = "asc",
  } = {}) {
    return useNuxtApp().$api<Record<string, any>>("/api/sites", {
      method: "GET",
      query: { page, search, limit, sort, order, org },
    });
  }

  return {
    sites,
    site,
    page,
    pages,
    pageRange,
    search,
    getSites,
    createSite,
    deleteSite,
    getSiteById,
    getAll,
  };
}
