import { Router } from 'express';

import { updatePassportExtra } from '../integrations/blocklet/passport';
import { blocklet } from '../libs/auth';
import { authenticate } from '../libs/security';
import { PaymentLink, PricingTable, Product } from '../store/models';

const router = Router();
const auth = authenticate<any>({ component: false, roles: ['owner', 'admin'] });

router.get('/', auth, async (_, res) => {
  const result = await blocklet.getRoles();
  res.json(result.roles);
});

router.put('/assign', auth, async (req, res) => {
  const { name, id } = req.body;

  if (!id) {
    return res.status(400).json({ message: 'payment entry or product id is required' });
  }
  if (!name) {
    return res.status(400).json({ message: 'passport name is required' });
  }

  if (id.startsWith('plink_')) {
    const doc = await PaymentLink.findByPk(id);
    if (!doc?.active) {
      return res.status(400).json({ message: 'payment link is not active' });
    }

    const result = await updatePassportExtra(name, { acquire: { pay: id } });
    return res.json(result);
  }

  if (id.startsWith('prctbl_')) {
    const doc = await PricingTable.findByPk(id);
    if (!doc?.active) {
      return res.status(400).json({ message: 'pricing table is not active' });
    }

    const result = await updatePassportExtra(name, { acquire: { pay: id } });
    return res.json(result);
  }

  if (id.startsWith('prod_')) {
    const doc = await Product.findByPk(id);
    if (!doc?.active) {
      return res.status(400).json({ message: 'product is not active' });
    }

    await doc.update({ metadata: { ...doc.metadata, passport: name } });
    const result = await updatePassportExtra(name, { payment: { product: id } });
    return res.json(result);
  }

  return res.status(400).json({ message: 'pay link is not support' });
});

router.delete('/assign/:name', auth, async (req, res) => {
  const result = await updatePassportExtra(req.params.name as string, {
    payment: { product: '' },
    acquire: { pay: '' },
  });
  return res.json(result);
});

export default router;
