import { Controller, Get, Header, UseGuards } from "@nestjs/common";
import { RateLimitGuard, RateLimit } from "@bff/core/rate-limiting/index.js";
import { Public, PublicNoSession } from "@bff/modules/auth/decorators/public.decorator.js";
import {
  parseInternetCatalog,
  parseSimCatalog,
  parseVpnCatalog,
  type InternetCatalogCollection,
  type SimCatalogCollection,
  type VpnCatalogCollection,
} from "@customer-portal/domain/services";
import { InternetServicesService } from "./application/internet-services.service.js";
import { SimServicesService } from "./application/sim-services.service.js";
import { VpnServicesService } from "./application/vpn-services.service.js";
import { SalesforceReadThrottleGuard } from "@bff/integrations/salesforce/guards/salesforce-read-throttle.guard.js";

const HEADER_CACHE_CONTROL = "Cache-Control";
const CACHE_CONTROL_PUBLIC = "public, max-age=300, s-maxage=300";

@Controller("public/services")
@Public()
@PublicNoSession()
@UseGuards(SalesforceReadThrottleGuard, RateLimitGuard)
export class PublicServicesController {
  constructor(
    private readonly internetCatalog: InternetServicesService,
    private readonly simCatalog: SimServicesService,
    private readonly vpnCatalog: VpnServicesService
  ) {}

  @Get("internet/plans")
  @RateLimit({ limit: 20, ttl: 60 }) // 20/min per IP+UA
  @Header(HEADER_CACHE_CONTROL, CACHE_CONTROL_PUBLIC) // safe: strictly non-personalized
  async getInternetCatalog(): Promise<InternetCatalogCollection> {
    const catalog = await this.internetCatalog.getCatalogData();
    return parseInternetCatalog(catalog);
  }

  @Get("sim/plans")
  @RateLimit({ limit: 20, ttl: 60 }) // 20/min per IP+UA
  @Header(HEADER_CACHE_CONTROL, CACHE_CONTROL_PUBLIC) // safe: strictly non-personalized
  async getSimCatalog(): Promise<SimCatalogCollection> {
    const catalog = await this.simCatalog.getCatalogData();
    return parseSimCatalog({
      ...catalog,
      plans: catalog.plans.filter(plan => !plan.simHasFamilyDiscount),
    });
  }

  @Get("vpn/plans")
  @RateLimit({ limit: 20, ttl: 60 }) // 20/min per IP+UA
  @Header(HEADER_CACHE_CONTROL, CACHE_CONTROL_PUBLIC) // safe: strictly non-personalized
  async getVpnCatalog(): Promise<VpnCatalogCollection> {
    const catalog = await this.vpnCatalog.getCatalogData();
    return parseVpnCatalog(catalog);
  }
}
