'use server'

import { cookies } from "next/headers";

import { APIError} from "@/util/api/error"
import { UserAuth, parseBasicAuth, getAssociatedUser } from "@/util/api/user"
import { Attachment, Auth, Bucket, DBState, Post, PostTag, Project, Tag, User, UserPerms,dbSync,sequelize} from "@/model/Models";
import Sequelize, { DataTypes } from "@sequelize/core";
import { SqliteColumnsDescription, SqliteDialect, SqliteQueryInterface } from "@sequelize/sqlite3";
import { hashPassword } from "@/util/Auth";


async function seedDatabase(queryInterface:SqliteQueryInterface<SqliteDialect>){
    
    const password = await hashPassword('changeme');
    const project = await Project.findOne({where: {
        readableIdentifier: 'blog'
    }}).then(e=> e ? e : Project.create({name:'General Blog',readableIdentifier:'blog'}));
    const user = await User.findOne({where: {
        username: 'admin'
    }}).then(e=> e ? e : User.create({username: 'admin', password: password, perms: {isAdmin: true}}, {include: User.associations.perms}));
    await Post.create({
        title: 'Test Post',
        content: `
        # Hello <ExampleComponent />
        this is some **test** markdown
        `,
        project_id: project.id,
        user_id: user.id
    })
    await Post.create({
        title: 'Test Post 2',
        content: `
        # Hello <ExampleComponent />
        this is amother post with some **test** markdown
        `,
        project_id: project.id,
        user_id: user.id
    })
}

async function trySetup(request:Request){
    await dbSync;

    const queryInterface = sequelize.queryInterface
    

    const version = (await DBState.findAll()).sort((a,b)=> ((a.version > b.version) ? 1 : -1)).map(a=>a.version)[0];

    

    switch(version){
        case 1:
            break;
        default:
            seedDatabase(queryInterface);
            const postsRows:SqliteColumnsDescription = await queryInterface.describeTable(Post.table.tableName).then(t=>t);
            if (!postsRows['project_id']) queryInterface.addColumn('Posts','project_id',{type: DataTypes.INTEGER, acceptsNull:()=>false,defaultValue:1})
            break;
    }

    return new Response(
        JSON.stringify(
        {
            test: await queryInterface.describeTable('Posts').then(t=>t)
        }),
        { 
            status: 200, 
            headers:{
                "Content-Type": "text/JSON" 
            } 
        }
    ); 
}

export async function GET(request:Request){
    try{
        return await trySetup(request);      
    }
    catch(e){
        if (e instanceof APIError){
            return new Response(e.info.responseText,{status:e.info.status});
        }
        else{
            throw e;
        }
    }
}
