import { useNavigate } from '@tanstack/react-router';
import { charactersRepo, notesRepo, questsRepo } from '@/lib/db/repositories';
import { getSystem, applyRest } from '@/lib/rules';
import type { SuggestAction } from '@/lib/assistant/advisors';

/**
 * One place that turns a signal's `SuggestAction` into a real mutation/navigation,
 * shared by the ambient signals bell and the Assistant page so behaviour can't
 * drift. `onDone` receives a short confirmation message for an aria-live region.
 */
export function useSignalAction(campaignId: string, onDone?: (msg: string) => void) {
  const navigate = useNavigate();

  return async (a: SuggestAction): Promise<void> => {
    switch (a.type) {
      case 'goto':
        void navigate(a.params ? { to: a.to, params: a.params } : { to: a.to });
        return;
      case 'longRest':
      case 'shortRest': {
        const c = await charactersRepo.get(a.characterId);
        if (!c) return;
        const opts = getSystem(c.system).restOptions;
        const opt = a.type === 'longRest'
          ? opts.find((o) => o.restoresHp) ?? opts.at(-1)
          : opts.find((o) => !o.restoresHp) ?? opts[0];
        if (opt) await charactersRepo.update(c.id, applyRest(c, opt));
        onDone?.(`Applied ${opt?.label ?? 'a rest'} for ${c.name}.`);
        return;
      }
      case 'completeQuest':
        await questsRepo.update(a.questId, { status: 'completed' });
        onDone?.('Quest marked complete.');
        return;
      case 'createNote':
        await notesRepo.create(campaignId, a.title);
        void navigate({ to: '/notes' });
        return;
    }
  };
}
