import { defineStore } from 'pinia';
import { ref } from 'vue';

interface SellerInfo {
  id: number;
  phone: string;
  contactName: string;
  email?: string;
  status: string;
  merchantId?: number;
  merchantStatus?: string;
}

export const useSellerStore = defineStore('seller', () => {
  const sellerToken = ref(uni.getStorageSync('sellerToken') || '');
  const sellerInfo = ref<SellerInfo | null>(uni.getStorageSync('sellerInfo') || null);

  function setSellerLogin(data: { accessToken: string; sellerInfo: SellerInfo }) {
    sellerToken.value = data.accessToken;
    sellerInfo.value = data.sellerInfo;
    uni.setStorageSync('sellerToken', data.accessToken);
    uni.setStorageSync('sellerInfo', data.sellerInfo);
  }

  function updateMerchantInfo(merchantId: number, merchantStatus: string) {
    if (sellerInfo.value) {
      sellerInfo.value = {
        ...sellerInfo.value,
        merchantId,
        merchantStatus,
      };
      uni.setStorageSync('sellerInfo', sellerInfo.value);
    }
  }

  function logoutSeller() {
    sellerToken.value = '';
    sellerInfo.value = null;
    uni.removeStorageSync('sellerToken');
    uni.removeStorageSync('sellerInfo');
  }

  function isSellerLoggedIn() {
    return !!sellerToken.value;
  }

  function hasMerchant() {
    return !!sellerInfo.value?.merchantId;
  }

  return { sellerToken, sellerInfo, setSellerLogin, updateMerchantInfo, logoutSeller, isSellerLoggedIn, hasMerchant };
});