const functions = require("firebase-functions");
const admin = require("firebase-admin");
const { onSchedule } = require("firebase-functions/v2/scheduler");

admin.initializeApp();
const bucket = admin.storage().bucket();

exports.deleteOldZipFiles = onSchedule(
    {
        schedule: "every 1 hours",
    },
    async () => {

        try {
            const prefixes = [
                "dev/GroupExpense/zip/",
                "dev/FamilyExpense/zip/",
                "dev/MessExpense/zip/",
                "local/GroupExpense/zip/",
                "local/FamilyExpense/zip/",
                "local/MessExpense/zip/",
                "prod/GroupExpense/zip/",
                "prod/FamilyExpense/zip/",
                "prod/MessExpense/zip/",
            ];

            const now = Date.now();

            for (const prefix of prefixes) {

                const [files] = await bucket.getFiles({ prefix });

                await Promise.all(
                    files.map(async (file) => {

                        if (!file.name || file.name.endsWith("/")) return;

                        try {
                            const [metadata] = await file.getMetadata();

                            const created = new Date(metadata.timeCreated).getTime();
                            const ageHours = (now - created) / (1000 * 60 * 60);

                            if (ageHours > 48) {
                                await file.delete();
                                console.log("Deleted:", file.name);
                            }

                        } catch (err) {
                            console.error("File error:", file.name, err);
                        }
                    })
                );
            }

            console.log("Cleanup completed");

        } catch (err) {
            console.error("Cleanup error:", err);
        }
    }
);