import notification from '@blocklet/sdk/service/notification';

import dayjs from 'dayjs';
import { Customer } from '../../store/models';

import logger from '../../libs/logger';

const handleUserUpdate = async ({ user }: { user: any }) => {
  logger.info('user Updated', {
    did: user.did,
    updated_at: user.updatedAt,
  });
  const customer = await Customer.findOne({
    where: {
      did: user.did,
    },
  });
  if (customer) {
    if (Math.abs(dayjs(customer.updated_at).diff(dayjs(user.updatedAt), 'minute')) <= 1) {
      logger.info(`skip customer update due to recent sync within 1 minute: ${customer.did}`);
      return;
    }
    const now = Math.floor(Date.now() / 1000);
    await customer.update({
      name: user.fullName || customer.name,
      email: user.email || customer.email,
      phone: user.phone || customer.phone,
      last_sync_at: now,
      address: Customer.formatAddressFromUser(user, customer),
    });
    logger.info(`customer info updated: ${customer.did}`);
  }
};

export async function initUserHandler() {
  await notification.on('user.updated', handleUserUpdate).catch((err: any) => {
    logger.error('failed to init user handler', err);
  });
}
