import { fetchWithAuth } from "./client";

// ── 类型定义 ────────────────────────────────────────────────────────────────────

export type ProjectStage =
  | "diagnosis"
  | "strategy"
  | "content"
  | "publishing"
  | "monitoring";

export type ProjectStatus = "active" | "paused" | "completed" | "archived";

export interface GeoProject {
  id: string;
  name: string;
  brand_name: string;
  description?: string;
  status: ProjectStatus;
  current_stage: ProjectStage;
  owner_id: string;
  client_id?: string;
  created_at: string;
  updated_at: string;
}

export interface CreateProjectPayload {
  name: string;
  brand_name: string;
  description?: string;
  client_id?: string;
}

export interface UpdateProjectPayload {
  name?: string;
  brand_name?: string;
  description?: string;
  status?: ProjectStatus;
  current_stage?: ProjectStage;
}

// ── API ────────────────────────────────────────────────────────────────────────

export interface LifecycleStats {
  total_projects: number;
  active_projects: number;
  completed_projects: number;
  contents_produced: number;
  avg_ai_citation_rate: number | null;
  current_stage_distribution: Record<string, number>;
}

export const lifecycleApi = {
  getStats: (token?: string) =>
    fetchWithAuth("/api/v1/lifecycle/projects/stats", {}, token) as Promise<LifecycleStats>,

  listProjects: (token?: string) =>
    fetchWithAuth("/api/v1/lifecycle/projects/", {}, token) as Promise<
      GeoProject[]
    >,
  getProject: (token?: string, projectId?: string) =>
    fetchWithAuth(
      `/api/v1/lifecycle/projects/${projectId}`,
      {},
      token
    ) as Promise<GeoProject>,
  createProject: (token?: string, data?: CreateProjectPayload) =>
    fetchWithAuth(
      "/api/v1/lifecycle/projects/",
      { method: "POST", body: JSON.stringify(data) },
      token
    ) as Promise<GeoProject>,
  updateProject: (
    token?: string,
    projectId?: string,
    data?: UpdateProjectPayload
  ) =>
    fetchWithAuth(
      `/api/v1/lifecycle/projects/${projectId}`,
      { method: "PUT", body: JSON.stringify(data) },
      token
    ) as Promise<GeoProject>,
  deleteProject: (token?: string, projectId?: string) =>
    fetchWithAuth(
      `/api/v1/lifecycle/projects/${projectId}`,
      { method: "DELETE" },
      token
    ),
  advanceStage: (token?: string, projectId?: string) =>
    fetchWithAuth(
      `/api/v1/lifecycle/projects/${projectId}/advance-stage`,
      { method: "POST" },
      token
    ) as Promise<GeoProject>,
};
