import { IStory, Story } from "../models/stories";
import { MongoClient } from "mongodb";
import mongoose from "mongoose";
import { uri, olduri } from "../lib/dbconfig";

import { Band } from "../models/band";

const cli = new MongoClient(olduri);

export default async function () {
	try {
		await cli.connect()

		await mongoose.connect(uri).then(() => console.log("connect'd"));

		const db = cli.db("rockfic_old")
		const col = db.collection("stories");
		const cursor = col.find({});
		for await(const s of cursor) {
			const feec = await db.collection("ficmas_wishes").findOne({_id: s.ficmas})
			const chall = await db.collection("challenges").findOne({_id: s.challenge})
			const nso: any & IStory = {
				...s,
				chapters: [],
				views: s.viewcount,
				reviews: s.numreviews,
				ficmas: feec?.wishid || null,
				challenge: chall?.chall_id || null,
				_id: s.id
			}
			delete nso.viewcount;
			delete nso.numchapters;
			delete nso.numreviews;
			const ns = new Story(nso)
			let idx = 1;
			for (const c of s.chapters) {
				const bandList = await Band.find({name: {$in: c.bands}})
				ns.chapters.push({
					title: c.chaptertitle,
					index: idx,
					id: c.chapterid,
					words: isNaN(parseInt(c.words)) ? 0 : parseInt(c.words),
					notes: c.notes,
					summary: c.summary,
					genre: c.genre,
					bands: bandList.map(a => a._id),
					characters: c.characters,
					relationships: c.relationships.map(a => a.split("/")),
					hidden: c.hidden,
					posted: c.posted,
					nsfw: c.rating.toLowerCase() == "adult",
					loggedInOnly: c.loggedinOnly,
					reviews: 0
					// TODO: correct this count in a later script :|
				})
				idx++;
			}
			await ns.save()
		}
	} catch(e) {
		console.error(e)
	} finally {
		return 0
	}
}
