import { fetchGeoInfo } from '@/lib/geoip';
import { db } from '@/lib/prisma';
import { resolvePlanPrice } from '@/modules/plan/services/plan-pricing.service';
import { parsePlanRules } from '@/modules/plan/services/plan-rules.service';
import type { AppContext } from '@/types/hono';

export async function listPlansHandler(c: AppContext) {
  const plans = await db.plan.findMany({
    orderBy: {
      price: 'asc',
    },
  });

  const countryParam = c.req.query('country');
  let countryCode: string | undefined;

  if (countryParam) {
    countryCode = countryParam;
  } else {
    const ip = c.req.header('x-forwarded-for')?.split(',')[0]?.trim() || '127.0.0.1';
    const geo = await fetchGeoInfo(ip);
    countryCode = geo?.countryCode || undefined;
  }

  return c.json(
    plans.map((plan) => {
      const rules = parsePlanRules(plan.rules);
      const resolved = resolvePlanPrice(Number(plan.price), rules, countryCode);
      return {
        code: plan.code,
        name: plan.name,
        price: resolved.amount,
        currency: resolved.currency,
        features: rules.features,
        limits: rules.limits,
      };
    })
  );
}
