import type {EventHandlerRequest, H3Event} from "h3";
import type {MySql2Database, MySqlRawQueryResult} from "drizzle-orm/mysql2";
import type {RedisClient} from "ioredis/built/connectors/SentinelConnector/types";
import type {Pool} from "mysql2/promise";
import type {HeaderAuth} from "~/types/nuxt.config";
import {blogMenu} from "~/drizzle/schema";
import {and, asc, desc, eq} from "drizzle-orm";

type InsertBlogMenu = typeof blogMenu.$inferInsert;

export class BlogMenuDB {
    private readonly db:MySql2Database<Record<string, never>>& { $client: Pool }
    private readonly redis: RedisClient
    constructor(event: H3Event<EventHandlerRequest>) {
        this.db = event.context.mysql
        this.redis = event.context.redis
    }
    
    // 插入目录
    async insertBlogMenu(insertBlogMenu: InsertBlogMenu, headerAuth: HeaderAuth): Promise<MySqlRawQueryResult> {
        const result = await this.db.insert(blogMenu).values({
            ...insertBlogMenu,
            createdBy: headerAuth.userId,
        })
        return result;
    }

    // 查询目录
    async getBlogMenu(headerAuth: HeaderAuth){
        // 指定用户的
        // 判断未删除的
        // 如果是登陆的，可以查看未公开的，如果不是，只能查看公开的
        return this.db
            .select()
            .from(blogMenu)
            .where(
                and(eq(blogMenu.createdBy, headerAuth.userId), eq(blogMenu.deleted, 0), headerAuth.isTrue ? undefined : eq(blogMenu.public, 1))
            ).orderBy(asc(blogMenu.sort), asc(blogMenu.createdAt));
    }
    // 获取指定目录id
    async getBlogMenuForBlogId(blogId: string, headerAuth: HeaderAuth):Promise<InsertBlogMenu> {
        const result = await this.db
            .select()
            .from(blogMenu)
            .where(
                and(eq(blogMenu.createdBy, headerAuth.userId), eq(blogMenu.deleted, 0), headerAuth.isTrue ? undefined : eq(blogMenu.public, 1), eq(blogMenu.id, blogId))
            ).limit(1);
        return result
    }
}