import { type UserSite } from 'src/types/timeTracking';
import { type SelectedSite } from 'src/utils/timeTracking';

import { REMOTE_WORK_SITE_VALUE } from '../../constants';

// Kept as a standalone, dependency-light module (only type imports plus a plain
// constant) so it stays unit-testable: jest can't resolve @material-hu subpath
// imports, so this file must not import anything that pulls them in at runtime.

/**
 * Reassigns the site shown on the period-detail map while keeping the marking
 * data of the entry the user actually selected.
 *
 * The map's source of truth is the clicked entry (`directSelectedSite`), which
 * already carries the correct `markingLocation`/`entrySource` for that specific
 * entry. While editing, the user can pick a different site from the dropdown;
 * only the site fields (`siteId`/`siteName`/`location`) must change — the
 * marking coordinate must stay tied to the original entry. Recomputing the
 * marking from a day-wide `find(e => e.type === entryType)` is what caused the
 * map to open on the wrong entry's location when a day had multiple pairs.
 *
 * Selecting "no site" (-1) or remote work collapses back to the siteless state
 * (`SiteMap` renders `siteId === -1` as the marking pin only), so changing the
 * dropdown to "no site"/remote — or discarding an edit on an entry that had
 * none — reverts the map instead of stranding the previously-selected site.
 */
export const applyFormSiteOverride = (
  base: SelectedSite | null,
  formSiteId: number | undefined,
  sites: UserSite[],
): SelectedSite | null => {
  if (!base) return null;

  // No usable form value (undefined / 0): keep the current map state.
  if (!formSiteId) return base;

  // "No site"/remote: collapse to the siteless state (siteId -1) and rebuild
  // `location` from the marking coordinate so the map shows just the pin.
  if (formSiteId === -1 || formSiteId === REMOTE_WORK_SITE_VALUE) {
    if (base.siteId === -1) return base;

    return {
      ...base,
      siteId: -1,
      siteName: '',
      location: base.markingLocation
        ? {
            latitude: base.markingLocation.latitude,
            longitude: base.markingLocation.longitude,
            tolerance: 0,
            address: '',
          }
        : base.location,
    };
  }

  if (formSiteId === base.siteId) return base;

  const site = sites.find(s => s.id === formSiteId);
  if (!site?.location) return base;

  return {
    ...base,
    siteId: site.id,
    siteName: site.name,
    location: site.location,
  };
};
