import { useState, useCallback } from "react"; import { API_URL } from "../config/authConstants"; /** * useSearchPosts — поиск объявлений по городу. * Ходит на GET /api/v1/posts/search?city=..., возвращает список без пагинации. * * @returns {Object} { posts, loading, error, searchPosts } */ export function useSearchPosts() { const [posts, setPosts] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const searchPosts = useCallback(async (city) => { setLoading(true); setError(""); try { const params = new URLSearchParams(); if (city) params.set("city", city); const res = await fetch(`${API_URL}/api/v1/posts/search?${params}`); if (!res.ok) throw new Error(`Error ${res.status}`); const data = await res.json(); const list = Array.isArray(data) ? data : []; const normalized = list.map(ad => ({ ...ad, type: ad.type ? ad.type.toLowerCase() : "loss" })); setPosts(normalized); return normalized; } catch (err) { setError(err.message || "Failed to search posts"); setPosts([]); return []; } finally { setLoading(false); } }, []); return { posts, loading, error, searchPosts }; }