import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { CloneOperation, CloneRequest, CloneStartResponse } from '@arboretum/shared';
import { api } from '../lib/api';
import { wsClient, type CloneEvent } from '../lib/ws-client';

// Suivi des opérations de clone (P12). État en mémoire alimenté par le push WS (topic 'clones') ;
// chaque opération survit au refresh côté serveur (GET /repos/clone/:id), non rechargé ici.
export const useCloneStore = defineStore('clone', () => {
  const operations = ref<CloneOperation[]>([]);
  let unsubscribe: (() => void) | null = null;

  function upsert(op: CloneOperation): void {
    const i = operations.value.findIndex((o) => o.id === op.id);
    if (i >= 0) operations.value.splice(i, 1, op);
    else operations.value.push(op);
  }

  function get(id: string): CloneOperation | undefined {
    return operations.value.find((o) => o.id === id);
  }

  function startRealtime(): void {
    unsubscribe ??= wsClient.subscribeClones((e: CloneEvent) => upsert(e.operation));
  }
  function stopRealtime(): void {
    unsubscribe?.();
    unsubscribe = null;
  }

  // Lance un clone ; la progression arrive ensuite par WS. Retourne l'operationId à suivre.
  async function clone(req: CloneRequest): Promise<string> {
    startRealtime(); // s'abonner AVANT de lancer pour ne manquer aucun event
    const res = await api.post<CloneStartResponse>('/api/v1/repos/clone', req);
    upsert({ id: res.operationId, state: 'pending', progress: null, phase: null, error: null, repoId: null, dest: req.dest });
    return res.operationId;
  }

  return { operations, get, clone, startRealtime, stopRealtime };
});
