import type { RoomProfile } from '../types/garden';

export type PlantSpaceLink = {
  id?: string;
  name?: string;
  commonName?: string;
  spaceId?: string | null;
  assignedSpaceId?: string;
  spaceName?: string;
  space?: string;
  location?: string;
};

export function normalizeGardenName(value?: string) {
  return (value || '').trim().toLowerCase().replace(/\s+/g, ' ');
}

export function resolvePlantSpaceId<T extends PlantSpaceLink>(plant: T, spaces: RoomProfile[]) {
  if (plant.spaceId && spaces.some(space => space.id === plant.spaceId)) return plant.spaceId;
  if (plant.assignedSpaceId && spaces.some(space => space.id === plant.assignedSpaceId)) return plant.assignedSpaceId;

  const legacySpaceName = plant.spaceName || plant.space || plant.location || plant.assignedSpaceId;
  if (!legacySpaceName) return undefined;

  const matchedSpace = spaces.find(space => normalizeGardenName(space.name) === normalizeGardenName(legacySpaceName));
  return matchedSpace?.id || null;
}

export function getPlantsForSpace<T extends { spaceId?: string | null }>(spaceId: string, plants: T[]) {
  return plants.filter(plant => plant.spaceId === spaceId);
}

export function findSpaceForPlant<T extends { spaceId?: string | null }>(plant: T, spaces: RoomProfile[]) {
  return plant.spaceId ? spaces.find(space => space.id === plant.spaceId) : undefined;
}
