import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  runsApi,
  type RunProfile,
  type RunStatus,
  type CreateRunProfileBody,
  type UpdateRunProfileBody,
} from '@/api/runs'

export const useRunsStore = defineStore('runs', () => {
  const profiles = ref<RunProfile[]>([])
  const loading = ref(false)

  async function fetch(wsID: string) {
    loading.value = true
    try {
      profiles.value = await runsApi.list(wsID)
    } finally {
      loading.value = false
    }
  }

  async function create(wsID: string, body: CreateRunProfileBody) {
    const p = await runsApi.create(wsID, body)
    profiles.value.unshift(p)
    return p
  }

  async function update(id: string, body: UpdateRunProfileBody) {
    const p = await runsApi.update(id, body)
    replace(p)
    return p
  }

  async function remove(id: string) {
    await runsApi.remove(id)
    profiles.value = profiles.value.filter((x) => x.id !== id)
  }

  async function start(id: string) {
    return applyStatus(id, await runsApi.start(id))
  }
  async function stop(id: string) {
    return applyStatus(id, await runsApi.stop(id))
  }
  async function restart(id: string) {
    return applyStatus(id, await runsApi.restart(id))
  }
  async function refreshStatus(id: string) {
    return applyStatus(id, await runsApi.status(id))
  }

  function replace(p: RunProfile) {
    profiles.value = profiles.value.map((x) => (x.id === p.id ? p : x))
  }

  // applyStatus 用 start/stop/restart/status 返回的轻量状态更新对应行的运行态字段。
  function applyStatus(id: string, s: RunStatus): RunStatus {
    profiles.value = profiles.value.map((x) =>
      x.id === id
        ? {
            ...x,
            status: s.status,
            started_at: s.started_at,
            last_exit_code: s.last_exit_code,
            last_error: s.last_error,
          }
        : x,
    )
    return s
  }

  return { profiles, loading, fetch, create, update, remove, start, stop, restart, refreshStatus }
})
