'use server';

import { revalidatePath, revalidateTag } from 'next/cache'
import { Bucket, Post, PostBucket, Project, User, dbSync } from "@/models";
import { Attributes, where } from "@sequelize/core";
import { getCookieAuth, userIsAdmin } from '../../actions';
import { ActionResult } from '../../ActionResult';
import { PostAttributesWithBuckets } from '@/models';

export async function deletePost(postID: number): Promise<ActionResult<boolean>> {
  await dbSync;
  // revalidatePath("/admin/man-post","page")
  if(! await userIsAdmin()) return {error:"Unauthorized, not deleting Post", result: false}
  const destroy = await Post.destroy({ where: { id: postID } });
  return {result: true};
}

export type GetPostsAttributes = {
  id: number;
  title: string;
  content: string;
  description: string;
  buckets: Attributes<Bucket>[];
  user: Attributes<User>;
  project: Attributes<Project>;
  createdAt: Date;
  updatedAt: Date;
}

export async function getPostsWithBucketsAndProject(): Promise<ActionResult<GetPostsAttributes[]>> {
  await dbSync;
  if(! await userIsAdmin()) return {error:"Unauthorized, not fetching Posts."}
  const posts = await Post.findAll({
    include: [
      {association: Post.associations.buckets, include: Bucket.associations.attachments},
      {association: Post.associations.user}, 
      {association: Post.associations.project}], 
    nest: false
  });
  return {result:JSON.parse(JSON.stringify(posts.map((e:Post)=>{
    return {
      id: e.id,
      title: e.title,
      content: e.content,
      description: e.description,
      buckets: e.buckets ? e.buckets : [],
      user: e.user,
      project: {
        id: e.project_id,
        name: e.project ? e.project.name : "",
        readableIdentifier: e.project ? e.project.readableIdentifier : "",
        posts: e.project ? e.project.posts : []
      },
      createdAt: e.createdAt,
      updatedAt: e.updatedAt
    } as GetPostsAttributes
  })))};
}

export async function getPosts(): Promise<ActionResult<Attributes<Post>[]>> {
  await dbSync;
  if(! await userIsAdmin()) return {error:"Unauthorized, not fetching Posts."}
  const posts = await Post.findAll();
  return {result:JSON.parse(JSON.stringify(posts))};
}

export async function updatePost(postAttributes: Partial<Attributes<Post>>): Promise<ActionResult<Attributes<Post>[]>> {
  await dbSync;
  console.log(`testing postattributes projectid ${postAttributes.project?.id} ${postAttributes.project_id}`)
  if(! await userIsAdmin()) return {error:"Unauthorized, not updating Post."}
  const post = await Post.update(postAttributes, {where:{id:postAttributes.id}});
  return {result:JSON.parse(JSON.stringify(post))};
}

export type PostServerActions = {
	deletePost: (id: number) => Promise<ActionResult<boolean>>;
	getPosts: () => Promise<ActionResult<GetPostsAttributes[]>>;
	getProjects: () => Promise<ActionResult<Attributes<Project>[]>>;
	savePost: (
		data: Partial<Attributes<Post>>
	) => Promise<ActionResult<Attributes<Post>[]>>;
};
