import { setUser as setUserLS, setRole as setRoleLS } from '../utils/storage'

const BASE = import.meta.env.VITE_API_BASE // e.g., http://localhost/landingpage1/auth-api

async function post(path, body) {
  const res = await fetch(`${BASE}/${path}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    credentials: 'include',
    body: JSON.stringify(body || {})
  })
  const data = await res.json().catch(() => ({}))
  if (!res.ok) throw new Error(data?.message || 'Server error')
  return data
}

export async function register({ name, email, username, password, role }) {
  const data = await post('register.php', { name, email, username, password, role })
  setRoleLS(data.role);
  setUserLS({
    id: data.id,
    name: data.name,
    email: data.email,
    username: data.username,
    role: data.role,
    streak_count: data.streak_count,
    last_login_date: data.last_login_date
  })
  return data
}

export async function login({ identifier, password }) {
  const data = await post('login.php', { identifier, password })
  setRoleLS(data.role);
  setUserLS({
    id: data.id,
    name: data.name,
    email: data.email,
    username: data.username,
    role: data.role,
    streak_count: data.streak_count,
    last_login_date: data.last_login_date
  })
  return data
}

// For Google login you'd implement a server endpoint to verify credential JWT.
// Here we simply route through email/name to create/find a student user in DB.
export async function loginGoogle({ email, name }) {
  // Reuse register endpoint semantics if needed; but better to create login_google.php.
  // For now, try to login; if not found, register as student.
  try {
    return await login({ email, password: '__google__' })
  } catch {
    return await register({ name: name || 'Siswa', email, password: '__google__', role: 'student' })
  }
}
