import { prisma } from '../config/database.js';

interface PlatformConfigCache {
  data: {
    blockedKeywords: string[];
    autoApprove: boolean;
    listingFee: number;
    commissionPercent: number;
    maxImagesPerListing: number;
    maxListingsFreeTier: number;
    promotionDayPrice: number;
    rentalCommissionPercent: number;
    rentalAutoApprove: boolean;
    maxRentalImagesPerListing: number;
    bookingExpiryHours: number;
    rentalPromotionDayPrice: number;
  } | null;
  timestamp: number;
}

const cache: PlatformConfigCache = { data: null, timestamp: 0 };
const CACHE_TTL = 60 * 1000; // 60 seconds

export async function getPlatformConfig() {
  const now = Date.now();
  if (cache.data && now - cache.timestamp < CACHE_TTL) {
    return cache.data;
  }

  const config = await prisma.platformConfig.findFirst();
  if (!config) {
    const defaults = {
      blockedKeywords: [] as string[],
      autoApprove: true,
      listingFee: 5.0,
      commissionPercent: 5.0,
      maxImagesPerListing: 6,
      maxListingsFreeTier: 5,
      promotionDayPrice: 2.99,
      rentalCommissionPercent: 10.0,
      rentalAutoApprove: false,
      maxRentalImagesPerListing: 10,
      bookingExpiryHours: 48,
      rentalPromotionDayPrice: 3.99,
    };
    cache.data = defaults;
    cache.timestamp = now;
    return defaults;
  }

  cache.data = {
    blockedKeywords: config.blockedKeywords,
    autoApprove: config.autoApprove,
    listingFee: config.listingFee,
    commissionPercent: config.commissionPercent,
    maxImagesPerListing: config.maxImagesPerListing,
    maxListingsFreeTier: config.maxListingsFreeTier,
    promotionDayPrice: config.promotionDayPrice,
    rentalCommissionPercent: config.rentalCommissionPercent,
    rentalAutoApprove: config.rentalAutoApprove,
    maxRentalImagesPerListing: config.maxRentalImagesPerListing,
    bookingExpiryHours: config.bookingExpiryHours,
    rentalPromotionDayPrice: config.rentalPromotionDayPrice,
  };
  cache.timestamp = now;
  return cache.data;
}

export function invalidateConfigCache() {
  cache.data = null;
  cache.timestamp = 0;
}

export function checkBlockedKeywords(text: string, blockedKeywords: string[]): string | null {
  const lowerText = text.toLowerCase();
  for (const keyword of blockedKeywords) {
    if (keyword && lowerText.includes(keyword.toLowerCase())) {
      return keyword;
    }
  }
  return null;
}
