import { defineStore } from 'pinia';
import { ref } from 'vue';
import type {
  CreateGitCredentialRequest,
  GitCredentialResponse,
  GitCredentialSummary,
  GitCredentialsListResponse,
  RemoteReposResponse,
  TestCredentialResponse,
  UpdateGitCredentialRequest,
} from '@arboretum/shared';
import { api } from '../lib/api';

// Connexions aux services git distants (P12). Les secrets ne transitent jamais en lecture
// (résumés hasSecret/secretLast4 seulement) ; la création/maj envoie le secret en écriture.
export const useGitConnectionsStore = defineStore('gitConnections', () => {
  const connections = ref<GitCredentialSummary[]>([]);
  const loading = ref(false);

  function upsert(c: GitCredentialSummary): void {
    const i = connections.value.findIndex((x) => x.id === c.id);
    if (i >= 0) connections.value.splice(i, 1, c);
    else connections.value.push(c);
  }

  async function fetchAll(): Promise<void> {
    loading.value = true;
    try {
      connections.value = (await api.get<GitCredentialsListResponse>('/api/v1/git-connections')).credentials;
    } finally {
      loading.value = false;
    }
  }

  async function create(req: CreateGitCredentialRequest): Promise<GitCredentialSummary> {
    const res = await api.post<GitCredentialResponse>('/api/v1/git-connections', req);
    upsert(res.credential);
    return res.credential;
  }

  async function update(id: string, patch: UpdateGitCredentialRequest): Promise<GitCredentialSummary> {
    const res = await api.patch<GitCredentialResponse>(`/api/v1/git-connections/${id}`, patch);
    upsert(res.credential);
    return res.credential;
  }

  async function remove(id: string): Promise<void> {
    await api.delete<{ ok: true }>(`/api/v1/git-connections/${id}`);
    connections.value = connections.value.filter((c) => c.id !== id);
  }

  async function test(id: string): Promise<TestCredentialResponse> {
    const res = await api.post<TestCredentialResponse>(`/api/v1/git-connections/${id}/test`);
    await fetchAll(); // rafraîchit lastTestedAt/testResult
    return res;
  }

  function listRemoteRepos(id: string, page = 1, search?: string): Promise<RemoteReposResponse> {
    const qs = new URLSearchParams({ page: String(page) });
    if (search) qs.set('search', search);
    return api.get<RemoteReposResponse>(`/api/v1/git-connections/${id}/repos?${qs.toString()}`);
  }

  return { connections, loading, fetchAll, create, update, remove, test, listRemoteRepos };
});
