import type { Zone } from '../office.ts';
import { byCodePoint, type WorldMap } from '../world-map.ts';

// Закрепление переговорок за встречами (спека 5.3).
export class MeetingRooms {
  private readonly map: WorldMap;
  private readonly alloc = new Map<string, string[]>();

  constructor(map: WorldMap) {
    this.map = map;
  }

  capacity(zoneId: string): number {
    return this.map.spotsInZone(zoneId).filter((s) => s.pose === 'sit').length;
  }

  roomsOf(meetingId: string): string[] {
    return this.alloc.get(meetingId) ?? [];
  }

  private free(): Zone[] {
    const taken = new Set([...this.alloc.values()].flat());
    return this.map.zones.filter((z) => z.kind === 'meeting' && !taken.has(z.id));
  }

  private byCapacityDesc(): Zone[] {
    return [...this.free()].sort((a, b) => this.capacity(b.id) - this.capacity(a.id) || byCodePoint(a.id, b.id));
  }

  private largestFree(): Zone | undefined {
    return this.byCapacityDesc()[0];
  }

  ensure(meetingId: string, need: number): string[] {
    const cur = this.alloc.get(meetingId);
    if (cur) return cur;
    const fit = [...this.free()]
      .sort((a, b) => this.capacity(a.id) - this.capacity(b.id) || byCodePoint(a.id, b.id))
      .find((z) => this.capacity(z.id) >= need);
    const room = fit ?? this.largestFree();
    if (!room) return [];
    this.alloc.set(meetingId, [room.id]);
    return [room.id];
  }

  // Ещё одна свободная переговорка за встречей: самая большая из тех, где есть подходящее свободное место
  // (комната без мест закрепилась бы впустую и осталась бы недоступной другим встречам до конца этой).
  addRoom(meetingId: string, hasFreeSpot: (zoneId: string) => boolean = () => true): string | null {
    const room = this.byCapacityDesc().find((z) => hasFreeSpot(z.id));
    if (!room) return null;
    this.alloc.set(meetingId, [...this.roomsOf(meetingId), room.id]);
    return room.id;
  }

  release(active: ReadonlySet<string>): void {
    for (const id of [...this.alloc.keys()]) if (!active.has(id)) this.alloc.delete(id);
  }

  allocations(): Record<string, string[]> {
    return Object.fromEntries(this.alloc);
  }
}
