import mongoose, { Schema, PopulatedDoc, Document, Model } from "mongoose";
import SequenceFactory from "mongoose-sequence";

const AutoIncrement = SequenceFactory(mongoose);

import { Chapter, IChapter } from "./chapter";
import { IUser } from "~/models/user";
import { Ficmas, IFicmas } from "~/models/challenges/ficmas";
import { IChallenge, Challenge } from "~/models/challenges/gen";
import { hasMigrated } from "~/lib/dbconfig";

export interface IStory {
	_id?: number;
	title: string;
	author: PopulatedDoc<IUser & Document>;
	chapters: IChapter[];
	recs: number;
	favs: number;
	reviews: number;
	views: number;
	completed: boolean;
	challenge: PopulatedDoc<IChallenge & Document> | null;
	ficmas: PopulatedDoc<IFicmas & Document> | null;
	downloads: number;
	lastUpdate: Date;
	posted: Date;
	coAuthor: PopulatedDoc<IUser & Document> | null;
}

const StorySchema = new mongoose.Schema<IStory>({
	_id: {
		type: Number,
	},
	title: {
		type: String,
	},
	author: {
		type: Number,
		ref: "User",
	},
	coAuthor: {
		type: Number,
		ref: "User",
		default: null,
	},
	chapters: [Chapter],
	recs: {
		type: Number,
		default: 0,
	},
	favs: {
		type: Number,
		default: 0,
	},
	reviews: {
		type: Number,
		default: 0,
	},
	views: {
		type: Number,
		default: 0,
	},
	completed: {
		type: Boolean,
		default: false,
	},
	challenge: {
		type: Number,
		ref: "Challenge",
		default: null,
	},
	ficmas: {
		type: Number,
		ref: "Ficmas",
		default: null,
	},
	downloads: {
		type: Number,
		default: 0,
	},
	lastUpdate: {
		type: Date,
		default: new Date(),
	},
	posted: {
		type: Date,
		default: new Date(),
	},
});
hasMigrated &&
	Chapter.plugin(AutoIncrement, { id: "chapterid", inc_field: "id" });
hasMigrated && StorySchema.plugin(AutoIncrement, { id: "storyid" });
export const Story: Model<IStory> =
	/* mongoose.models.Story || */ mongoose.model(
		"Story",
		StorySchema,
		"stories",
	);
