import axios from 'axios'

const api = axios.create({
  baseURL: '/api',
  timeout: 30000,
})

// --- Projects ---
export function listProjects() {
  return api.get('/projects').then(r => r.data)
}

export function getProject(id) {
  return api.get(`/projects/${id}`).then(r => r.data)
}

export function createProject(data) {
  return api.post('/projects', data).then(r => r.data)
}

export function updateProject(id, data) {
  return api.put(`/projects/${id}`, data).then(r => r.data)
}

export function deleteProject(id) {
  return api.delete(`/projects/${id}`).then(r => r.data)
}

// --- Build & Run ---
export function triggerBuild(id) {
  return api.post(`/projects/${id}/build`).then(r => r.data)
}

export function startProject(id) {
  return api.post(`/projects/${id}/start`).then(r => r.data)
}

export function stopProject(id) {
  return api.post(`/projects/${id}/stop`).then(r => r.data)
}

export function restartProject(id) {
  return api.post(`/projects/${id}/restart`).then(r => r.data)
}

export function getBuilds(id) {
  return api.get(`/projects/${id}/builds`).then(r => r.data)
}

export function getBuildLog(id, buildId) {
  return api.get(`/projects/${id}/logs/${buildId}`).then(r => r.data)
}

// --- Upload ---
export function uploadFile(id, formData) {
  return api.post(`/projects/${id}/upload`, formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  }).then(r => r.data)
}

// --- Deploy Config ---
export function getDeployConfig(id) {
  return api.get(`/projects/${id}/deploy-config`).then(r => r.data)
}

export function updateDeployConfig(id, data) {
  return api.put(`/projects/${id}/deploy-config`, data).then(r => r.data)
}

export function deleteDeployConfig(id) {
  return api.delete(`/projects/${id}/deploy-config`).then(r => r.data)
}

// --- Deploy Execution ---
export function triggerDeploy(id) {
  return api.post(`/projects/${id}/deploy`).then(r => r.data)
}

export function getDeployRecords(id) {
  return api.get(`/projects/${id}/deploy-records`).then(r => r.data)
}

export function getDeployLog(id, deployId) {
  return api.get(`/projects/${id}/deploy-records/${deployId}/log`).then(r => r.data)
}

// --- SSE ---
export function createLogStream(id) {
  return new EventSource(`/api/projects/${id}/logs/stream`)
}
