import { Router } from "express";
import { LoyaltyTxn } from "@/db/models";
import { asyncHandler } from "@/lib/errors";
import { requireAuth, requireRoles } from "@/middleware/auth";
import { toPlain } from "@/lib/serialize";
import { ensureLoyalty } from "@/services/loyalty";
import { getCommerceSettings } from "@/services/commerce";
import { isLoyaltyMysql, isSettingsMysql } from "@/db/activeDatabase";
import { listLoyaltyTxnsMysql, loyaltyTxnToApi } from "@/db/mysql/loyalty";

export const loyaltyRouter = Router();

loyaltyRouter.get(
  "/",
  requireAuth,
  requireRoles("CUSTOMER", "ADMIN"),
  asyncHandler(async (req, res) => {
    const account = await ensureLoyalty(req.user!.id);
    const settings = await getCommerceSettings();

    if (isLoyaltyMysql()) {
      const txns = await listLoyaltyTxnsMysql(req.user!.id, 40);
      res.json({
        points: (account as any).points,
        transactions: txns.map(loyaltyTxnToApi),
        settings: {
          loyaltyEnabled: settings.loyaltyEnabled,
          pointsPerLyd: settings.pointsPerLyd,
          tndPerPoint: settings.tndPerPoint,
          minRedeemPoints: settings.minRedeemPoints,
          maxRedeemPercentOfSubtotal: settings.maxRedeemPercentOfSubtotal,
        },
        _db: "mysql",
        _settingsDb: isSettingsMysql() ? "mysql" : "mongodb",
      });
      return;
    }

    const txns = await LoyaltyTxn.find({ userId: req.user!.id })
      .sort({ createdAt: -1 })
      .limit(40)
      .lean();
    res.json({
      points: (account as any).points,
      transactions: txns.map(toPlain),
      settings: {
        loyaltyEnabled: settings.loyaltyEnabled,
        pointsPerLyd: settings.pointsPerLyd,
        tndPerPoint: settings.tndPerPoint,
        minRedeemPoints: settings.minRedeemPoints,
        maxRedeemPercentOfSubtotal: settings.maxRedeemPercentOfSubtotal,
      },
      _db: "mongodb",
      _settingsDb: isSettingsMysql() ? "mysql" : "mongodb",
    });
  }),
);
