/**
 * Region-related utilities for flexible region matching
 * Consolidates duplicated region code from utils.ts, recommend.ts, and servers.ts
 */

/**
 * Country name to region code/city mapping for flexible region matching
 * Note: Use specific city names to avoid LIKE pattern collisions (e.g., 'de' matches 'Delhi')
 */
export const COUNTRY_NAME_TO_REGIONS: Record<string, string[]> = {
  'korea': ['seoul', 'koreacentral', 'kr', 'ap-northeast-2'],
  'south korea': ['seoul', 'koreacentral', 'kr', 'ap-northeast-2'],
  'japan': ['tokyo', 'osaka', 'ap-northeast-1', 'ap-northeast-3'],
  'singapore': ['singapore', 'ap-southeast-1'],
  'indonesia': ['jakarta', 'ap-southeast-3'],
  'australia': ['sydney', 'melbourne', 'au-east', 'ap-southeast-2'],
  'india': ['mumbai', 'delhi', 'chennai', 'ap-south'],
  'usa': ['us-east', 'us-west', 'us-central', 'america'],
  'us': ['us-east', 'us-west', 'us-central', 'america'],
  'united states': ['us-east', 'us-west', 'us-central', 'america'],
  'uk': ['london', 'uk-south', 'eu-west-2'],
  'united kingdom': ['london', 'uk-south', 'eu-west-2'],
  'germany': ['frankfurt', 'eu-central', 'eu-west-3'],
  'france': ['paris', 'eu-west-3'],
  'netherlands': ['amsterdam', 'eu-west-1'],
  'brazil': ['sao paulo', 'sa-east'],
  'canada': ['toronto', 'montreal', 'ca-central'],
};

/**
 * Escape LIKE pattern special characters
 */
export function escapeLikePattern(pattern: string): string {
  return pattern.replace(/[%_\\]/g, '\\$&');
}

/**
 * Default region filter SQL for legacy regions table (when no region is specified)
 * Used in /api/recommend for backward compatibility
 */
export const DEFAULT_REGION_FILTER_SQL = `(
  -- Korea (Seoul)
  r.region_code IN ('icn', 'ap-northeast-2') OR
  LOWER(r.region_name) LIKE '%seoul%' OR
  -- Japan (Tokyo, Osaka)
  r.region_code IN ('nrt', 'itm', 'ap-northeast-1', 'ap-northeast-3') OR
  LOWER(r.region_code) LIKE '%tyo%' OR
  LOWER(r.region_code) LIKE '%osa%' OR
  LOWER(r.region_name) LIKE '%tokyo%' OR
  LOWER(r.region_name) LIKE '%osaka%' OR
  -- Singapore
  r.region_code IN ('sgp', 'ap-southeast-1') OR
  LOWER(r.region_code) LIKE '%sin%' OR
  LOWER(r.region_code) LIKE '%sgp%' OR
  LOWER(r.region_name) LIKE '%singapore%'
)`;

/**
 * Default region filter SQL for anvil_regions (when no region is specified)
 * Used in both /api/recommend and /api/servers
 */
export const DEFAULT_ANVIL_REGION_FILTER_SQL = `(
  -- Korea (Seoul)
  ar.name IN ('icn', 'ap-northeast-2') OR
  LOWER(ar.display_name) LIKE '%seoul%' OR
  -- Japan (Tokyo, Osaka)
  ar.name IN ('nrt', 'itm', 'ap-northeast-1', 'ap-northeast-3') OR
  LOWER(ar.name) LIKE '%tyo%' OR
  LOWER(ar.name) LIKE '%osa%' OR
  LOWER(ar.display_name) LIKE '%tokyo%' OR
  LOWER(ar.display_name) LIKE '%osaka%' OR
  -- Singapore
  ar.name IN ('sgp', 'ap-southeast-1') OR
  LOWER(ar.name) LIKE '%sin%' OR
  LOWER(ar.name) LIKE '%sgp%' OR
  LOWER(ar.display_name) LIKE '%singapore%'
)`;

/**
 * Build flexible region matching SQL conditions for legacy regions table
 * Returns SQL conditions and parameters for use in prepared statements
 */
export function buildFlexibleRegionConditions(
  regions: string[]
): { conditions: string[]; params: (string | number)[] } {
  const conditions: string[] = [];
  const params: (string | number)[] = [];

  for (const region of regions) {
    const lowerRegion = region.toLowerCase();
    const expandedRegions = COUNTRY_NAME_TO_REGIONS[lowerRegion] || [lowerRegion];
    const allRegions = [lowerRegion, ...expandedRegions];

    for (const r of allRegions) {
      const escapedRegion = escapeLikePattern(r);
      conditions.push(`(
        LOWER(r.region_code) = ? OR
        LOWER(r.region_code) LIKE ? ESCAPE '\\' OR
        LOWER(r.region_name) LIKE ? ESCAPE '\\' OR
        LOWER(r.country_code) = ?
      )`);
      params.push(r, `%${escapedRegion}%`, `%${escapedRegion}%`, r);
    }
  }

  return { conditions, params };
}

/**
 * Build flexible region matching SQL conditions for anvil_regions
 * Returns SQL conditions and parameters for use in prepared statements
 */
export function buildFlexibleRegionConditionsAnvil(
  regions: string[]
): { conditions: string[]; params: (string | number)[] } {
  const conditions: string[] = [];
  const params: (string | number)[] = [];

  for (const region of regions) {
    const lowerRegion = region.toLowerCase();
    const expandedRegions = COUNTRY_NAME_TO_REGIONS[lowerRegion] || [lowerRegion];
    const allRegions = [lowerRegion, ...expandedRegions];

    for (const r of allRegions) {
      const escapedRegion = escapeLikePattern(r);
      conditions.push(`(
        LOWER(ar.name) = ? OR
        LOWER(ar.name) LIKE ? ESCAPE '\\' OR
        LOWER(ar.display_name) LIKE ? ESCAPE '\\' OR
        LOWER(ar.country_code) = ?
      )`);
      params.push(r, `%${escapedRegion}%`, `%${escapedRegion}%`, r);
    }
  }

  return { conditions, params };
}
