import type { Credentials, Task } from '../types'
import { session } from '../stores/session'

const API_BASE = 'http://localhost:8080/api/v1'

function headers() {
  const h: Record<string, string> = { 'Content-Type': 'application/json' }
  if (session.token) h.Authorization = `Bearer ${session.token}`
  return h
}

async function handle<T>(response: Response): Promise<T> {
  if (!response.ok) {
    const body = await response.text()
    throw new Error(body || `Request failed: ${response.status}`)
  }
  if (response.status === 204) return undefined as T
  return (await response.json()) as T
}

export async function register(credentials: Credentials) {
  const response = await fetch(`${API_BASE}/auth/register`, {
    method: 'POST',
    headers: headers(),
    body: JSON.stringify(credentials),
  })
  return handle<{ id: number; email: string }>(response)
}

export async function login(credentials: Credentials) {
  const response = await fetch(`${API_BASE}/auth/login`, {
    method: 'POST',
    headers: headers(),
    body: JSON.stringify(credentials),
  })
  return handle<{ token: string }>(response)
}

export async function logout() {
  const response = await fetch(`${API_BASE}/auth/logout`, {
    method: 'POST',
    headers: headers(),
  })
  return handle<void>(response)
}

export async function listTasks() {
  const response = await fetch(`${API_BASE}/tasks`, { headers: headers() })
  return handle<Task[]>(response)
}

export async function createTask(payload: Partial<Task>) {
  const response = await fetch(`${API_BASE}/tasks`, {
    method: 'POST',
    headers: headers(),
    body: JSON.stringify(payload),
  })
  return handle<Task>(response)
}

export async function updateTask(id: number, payload: Partial<Task>) {
  const response = await fetch(`${API_BASE}/tasks/${id}`, {
    method: 'PUT',
    headers: headers(),
    body: JSON.stringify(payload),
  })
  return handle<Task>(response)
}

export async function deleteTask(id: number) {
  const response = await fetch(`${API_BASE}/tasks/${id}`, {
    method: 'DELETE',
    headers: headers(),
  })
  return handle<void>(response)
}
