import { Knex } from "knex";

export async function up(knex: Knex) {
	await knex.schema.createTable("schema_migration", (b) => {
		b.string("version");
		b.boolean("dirty");
	});

	await knex.schema.createTable("users", (b) => {
		b.string("username").primary().comment("user's login id");
		b.string("password_hash", 64).notNullable();
		b.string("password_salt", 64).notNullable();
	});
	await knex.schema.createTable("document", (b) => {
		b.increments("id").primary();
		b.string("title").notNullable();
		b.string("content_type", 16).notNullable();
		b.string("basepath", 256).notNullable().comment("directory path for resource");
		b.string("filename", 256).notNullable().comment("filename");
		b.string("content_hash").nullable();
		b.json("additional").nullable();
		b.integer("created_at").notNullable();
		b.integer("modified_at").notNullable();
		b.integer("deleted_at");
		b.index("content_type", "content_type_index");
	});
	await knex.schema.createTable("tags", (b) => {
		b.string("name").primary();
		b.text("description");
	});
	await knex.schema.createTable("doc_tag_relation", (b) => {
		b.integer("doc_id").unsigned().notNullable();
		b.string("tag_name").notNullable();
		b.foreign("doc_id").references("document.id");
		b.foreign("tag_name").references("tags.name");
		b.primary(["doc_id", "tag_name"]);
	});
	await knex.schema.createTable("permissions", (b) => {
		b.string("username").notNullable();
		b.string("name").notNullable();
		b.primary(["username", "name"]);
		b.foreign("username").references("users.username");
	});
	// create admin account.
	await knex
		.insert({
			username: "admin",
			password_hash: "unchecked",
			password_salt: "unchecked",
		})
		.into("users");
}

export async function down(knex: Knex) {
	throw new Error("Downward migrations are not supported. Restore from backup.");
}