import { ref } from 'vue';
import { api } from 'src/boot/axios';
import { defineStore } from 'pinia';

import { Pagination } from '../types';
import { Branch } from '../branch/types';

import useFlowStore from '../flow';

const useMyBranch = defineStore('useMyBranchStore', () => {
  const myBranch = ref<Branch[]>();
  const currentMyBranch = ref<Branch>();

  const flowStore = useFlowStore();
  async function fetchListOptionBranch<
    Options extends {
      page?: number;
      pageSize?: number;
      zipCode?: string;
      query?: string;
      tree?: boolean;
      filter?: 'head' | 'sub';
    },
    Data extends Pagination<Branch[]>,
  >(opts?: Options): Promise<Data | false> {
    const params = new URLSearchParams();

    for (const [k, v] of Object.entries(opts || {})) {
      v !== undefined && params.append(k, v.toString());
    }

    const query = params.toString();

    const res = await api.get<Data>(
      `/branch${(params && '?'.concat(query)) || ''}`,
      {
        headers: { 'X-Rtid': flowStore.rtid },
      },
    );

    if (res && res.status === 200) {
      return res.data;
    }
    return false;
  }

  async function fetchListMyBranch(userId: string) {
    const res = await api.get<Pagination<Branch[]>>(`/branch`, {
      headers: {
        'X-Rtid': flowStore.rtid,
      },
    });

    if (!res) return false;
    if (res.status === 200) {
      myBranch.value = res.data.result;
      return res.data;
    }

    return false;
  }

  return {
    myBranch,
    currentMyBranch,

    fetchListOptionBranch,
    fetchListMyBranch,
  };
});

export default useMyBranch;
