import { Router } from 'express';
import Joi from 'joi';
import type { WhereOptions } from 'sequelize';

import { createListParamSchema, getOrder } from '../libs/api';
import { authenticate } from '../libs/security';
import { Event, WebhookAttempt, WebhookEndpoint } from '../store/models';
import { blocklet } from '../libs/auth';
import logger from '../libs/logger';

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

const schema = createListParamSchema<{
  event_id?: string;
  webhook_endpoint_id?: string;
}>({
  event_id: Joi.string().empty(''),
  webhook_endpoint_id: Joi.string().empty(''),
});
router.get('/', auth, async (req, res) => {
  const { page, pageSize, ...query } = await schema.validateAsync(req.query, { stripUnknown: true });
  const where: WhereOptions<WebhookAttempt> = {};

  if (typeof query.livemode === 'boolean') {
    where.livemode = query.livemode;
  }
  if (query.event_id) {
    where.event_id = query.event_id;
  }
  if (query.webhook_endpoint_id) {
    where.webhook_endpoint_id = query.webhook_endpoint_id;
  }

  try {
    const { rows: list, count } = await WebhookAttempt.findAndCountAll({
      where,
      order: getOrder(req.query, [['created_at', 'DESC']]),
      offset: (page - 1) * pageSize,
      limit: pageSize,
      include: [
        { model: Event, as: 'event' },
        { model: WebhookEndpoint, as: 'endpoint' },
      ],
    });

    const updatedList = await Promise.all(
      list.map(async (attempt: any) => {
        const updated = attempt.toJSON();
        if (updated.event?.request?.requested_by) {
          const { user } = await blocklet.getUser(updated.event.request.requested_by);
          if (user) {
            updated.event.requestInfo = user;
          }
        }
        return updated;
      })
    );
    res.json({ count, list: updatedList, paging: { page, pageSize } });
  } catch (err) {
    logger.error(err);
    res.json({ count: 0, list: [], paging: { page, pageSize } });
  }
});

export default router;
