const API_ORIGIN = (import.meta.env.VITE_API_BASE_URL ?? '').replace(/\/$/, '');
const API = `${API_ORIGIN}/api/v1`;

export interface User {
  id: number;
  username: string;
  created_at: string;
}

export interface UserProfile extends User {
  projects: Project[];
}

export interface ReleaseSummary {
  id: number;
  version: string;
  channel: string;
  artifact_url?: string;
  artifact_name?: string;
  source_commit?: string;
  created_at: string;
}

export interface Project {
  id: number;
  owner: string;
  slug: string;
  name: string;
  description: string;
  repository_url?: string;
  spec_path?: string;
  visibility: string;
  created_at: string;
  updated_at: string;
  releases?: ReleaseSummary[];
  spec_functions?: number;
  implementations?: number;
}

async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
  const response = await fetch(`${API}${path}`, {
    credentials: 'same-origin',
    ...options,
    headers: { Accept: 'application/json', ...(options.body ? { 'Content-Type': 'application/json' } : {}), ...options.headers },
  });
  if (!response.ok) {
    const value = await response.json().catch(() => ({})) as { detail?: string };
    throw new Error(value.detail || `Request failed (${response.status})`);
  }
  return response.status === 204 ? undefined as T : response.json() as Promise<T>;
}

export const platformApi = {
  me: () => request<User>('/auth/me'),
  signup: (body: { username: string; email: string; password: string }) =>
    request<User>('/auth/signup', { method: 'POST', body: JSON.stringify(body) }),
  login: (body: { username: string; password: string }) =>
    request<User>('/auth/login', { method: 'POST', body: JSON.stringify(body) }),
  logout: () => request<void>('/auth/logout', { method: 'POST' }),
  projects: () => request<Project[]>('/projects'),
  user: (username: string) => request<UserProfile>(`/users/${encodeURIComponent(username)}`),
  myProjects: () => request<Project[]>('/me/projects'),
  project: (owner: string, slug: string) => request<Project>(`/projects/${encodeURIComponent(owner)}/${encodeURIComponent(slug)}`),
  createProject: (body: { slug: string; name: string; description: string; repository_url: string; spec_path: string }) =>
    request<Project>('/projects', { method: 'POST', body: JSON.stringify(body) }),
  updateProject: (owner: string, slug: string, body: { name: string; description: string; repository_url: string; spec_path: string }) =>
    request<Project>(`/projects/${encodeURIComponent(owner)}/${encodeURIComponent(slug)}`, { method: 'PUT', body: JSON.stringify(body) }),
  createToken: () => request<{ token: string; label: string }>('/auth/tokens', { method: 'POST', body: JSON.stringify({ label: 'Polyform CLI' }) }),
};
