import regionsData from "@/lib/data/regions.json";

export interface RegionNode {
  name: string;
  longitude: number;
  children?: Record<string, RegionNode>;
}

export type RegionsData = Record<string, RegionNode>;

export const regions = regionsData as RegionsData;

export function getProvinces(): { code: string; name: string }[] {
  return Object.entries(regions).map(([code, node]) => ({
    code,
    name: node.name,
  }));
}

export function getCities(provinceCode: string): { code: string; name: string }[] {
  const province = regions[provinceCode];
  if (!province?.children) {
    return [];
  }
  return Object.entries(province.children).map(([code, node]) => ({
    code,
    name: node.name,
  }));
}

export function getRegionLocation(
  provinceCode: string,
  cityCode: string,
): { name: string; longitude: number } | null {
  const province = regions[provinceCode];
  if (!province) {
    return null;
  }
  const city = province.children?.[cityCode];
  if (city) {
    return {
      name: `${province.name}${city.name}`,
      longitude: city.longitude,
    };
  }
  return {
    name: province.name,
    longitude: province.longitude,
  };
}
