import axios from "axios";

const API_URL = "https://testowe.zikor.pl/api/v1";

export async function listNotices() {
    const response = await fetch(`${API_URL}/notices/get/all`);
    const data = await response.json();
    if (!response.ok) {
        throw new Error(response.toString());
    }
    return data;
}

export async function getNoticeById(noticeId) {
    const response = await fetch(`${API_URL}/notices/get/${noticeId}`);

    const data = await response.json();
    if (!response.ok) {
        throw new Error("Error");
    }
    return data;
}

export async function getImageByNoticeId(noticeId) {
    let imageUrl;
    try {
        const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`);

        const imageName = listResponse.data[0];
        imageUrl = `${API_URL}/images/get/${imageName}`;

        console.log(`Pobrano zdjęcie o nazwie: ${imageName}`);

        return imageUrl;
    } catch (err) {
        console.log(`Zdjęcie nie istnieje dla notice o id: ${noticeId}`);
        imageUrl = "https://http.cat/404.jpg";
        return imageUrl;
    }
}