'use server';
import { APIError } from "@/util/api/error";
import { Bucket, Post } from "@/models";
import { randomUUID, UUID } from "crypto";
import { mkdirSync, writeFile } from "fs";

export async function addToNewBucketForPost(postid: number): Promise<Bucket> {
    Post.sync();
    const post: Post | null = await Post.findOne({ where: { id: postid } });

    if (!post) throw new APIError({ status: 500, responseText: "invalid postid" });
    const bucket = await post.createBucket({ id: randomUUID() });
    return bucket;
}

export async function writeFilesToFS(uuid: UUID, files: any[]): Promise<{ success: boolean, filePaths: string[] }> {

    type FileArrayEntryWithPromise = {
        name: string;
        content: Promise<ReadableStreamReadResult<Uint8Array>> | ReadableStreamReadResult<Uint8Array>
    }
    type FileArrayEntry = {
        name: string;
        content: ReadableStreamReadResult<Uint8Array>
    };

    // Resolve promises
    const fileArray: FileArrayEntryWithPromise[] = await Promise.all(files.map((file: File) => {
        return { 'name': (() => file.name)(), 'content': file.stream().getReader().read() };
    }));



    let finalFileArray: FileArrayEntry[] = await (
        async () => {
            for (let file in fileArray) {
                fileArray[file].content = await fileArray[file].content
            }
            return [...fileArray as FileArrayEntry[]]
        })();

    // Make Bucket Directory
    mkdirSync(`./bucket/${uuid}/`, { recursive: true })

    // Write files to filesystem
    for (let file in finalFileArray) {
        writeFile(`./bucket/${uuid}/${finalFileArray[file].name}`
            , Buffer.from(finalFileArray[file].content.value as Uint8Array)
            , (e) => { console.log(e) });
    }
    return {
        success: true,
        filePaths: finalFileArray.map((e) => e.name)
    }
}

export async function addToExistingBucket(bucketid: number): Promise<Bucket> {
	const bucket = await Bucket.findOne({
		where: { id: bucketid },
		include: { association: Bucket.associations.posts },
	});
	if (!bucket)
		throw new APIError({ status: 500, responseText: "invalid bucketid" });
	return bucket;
}