#include "profile.h"
#include "buffer.h"
#include <windows.h>
#include <stdio.h>

static bool profile_has_database(const wchar_t* profile_path, const wchar_t* db_relative_path) {
    wchar_t full_path[MAX_PATH_LEN];
    swprintf_s(full_path, MAX_PATH_LEN, L"%s\\%s", profile_path, db_relative_path);

    DWORD attrs = GetFileAttributesW(full_path);
    return (attrs != INVALID_FILE_ATTRIBUTES && !(attrs & FILE_ATTRIBUTE_DIRECTORY));
}

static bool is_profile_directory(const wchar_t* path) {
    const wchar_t* check_paths[] = { L"Network\\Cookies", L"Login Data", L"Web Data" };
    for (int i = 0; i < 3; i++) {
        if (profile_has_database(path, check_paths[i])) return true;
    }
    return false;
}

ProfileList* profile_find_all(const wchar_t* user_data_root) {
    ProfileList* list = profile_list_create(10);
    if (!list) return NULL;

    if (is_profile_directory(user_data_root)) {
        profile_list_add(list, user_data_root);
    }

    wchar_t search_path[MAX_PATH_LEN];
    swprintf_s(search_path, MAX_PATH_LEN, L"%s\\*", user_data_root);

    WIN32_FIND_DATAW find_data;
    HANDLE hFind = FindFirstFileW(search_path, &find_data);

    if (hFind != INVALID_HANDLE_VALUE) {
        do {
            if (wcscmp(find_data.cFileName, L".") == 0 || wcscmp(find_data.cFileName, L"..") == 0)
                continue;

            if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
                wchar_t current_path[MAX_PATH_LEN];
                swprintf_s(current_path, MAX_PATH_LEN, L"%s\\%s", user_data_root, find_data.cFileName);

                if (is_profile_directory(current_path)) {
                    profile_list_add(list, current_path);
                }
            }
        } while (FindNextFileW(hFind, &find_data));
        FindClose(hFind);
    }

    return list;
}