import type { GitRepo } from "../types";

const API_BASE_URL = "https://git.luke-else.co.uk/api/v1";
export const IMAGE_URL_SUFFIX = "/raw/branch/main/assets/images/main.png";


export async function fetchRepos(): Promise<GitRepo[]> {
    try {
        console.log("Fetching repos...");
        const response = await fetch(`${API_BASE_URL}/repos/search?sort=updated&order=desc&limit=12`, {
            headers: {
                // "Authorization": `token ${ACCESS_TOKEN}`,
                "Content-Type": "application/json"
            }
        });

        if (!response.ok) {
            throw new Error(`Error: ${response.statusText}`);
        }

        const data: { data: GitRepo[] } = await response.json();
        return data.data; // Extract the list of repositories
    } catch (error) {
        console.error("Failed to fetch repos:", error);
        return [];
    }
}

export function timeSince(inputDate: Date | string): string {
    const date = new Date(inputDate); // Ensure it's a Date object
    if (isNaN(date.getTime())) {
        throw new Error("Invalid date provided");
    }

    const now: Date = new Date();
    const diffInMs: number = now.getTime() - date.getTime();
    const diffInSeconds: number = Math.floor(diffInMs / 1000);
    const diffInMinutes: number = Math.floor(diffInSeconds / 60);
    const diffInHours: number = Math.floor(diffInMinutes / 60);
    const diffInDays: number = Math.floor(diffInHours / 24);
    const diffInMonths: number = Math.floor(diffInDays / 30); // Approximate
    const diffInYears: number = Math.floor(diffInDays / 365); // Approximate

    if (diffInDays === 0) return "Today";
    if (diffInDays === 1) return "Yesterday";
    if (diffInDays < 7) return `${diffInDays} days ago`;
    if (diffInDays < 30) return `${Math.floor(diffInDays / 7)} week${diffInDays >= 14 ? 's' : ''} ago`;
    if (diffInMonths < 12) return `${diffInMonths} month${diffInMonths > 1 ? 's' : ''} ago`;
    return `${diffInYears} year${diffInYears > 1 ? 's' : ''} ago`;
}

export async function checkImage(repo: GitRepo): Promise<boolean> {
    try {
        const URL = repo.html_url + IMAGE_URL_SUFFIX;
        console.log("Checking image:", URL);
        const response = await fetch(URL);
        if (response.ok) {
            console.log("Image found!");
            return true;
        } else {
            console.log("Image not found!");
            return false;
        }
    } catch (error) {
        return false;
    }
}