import { FastifyReply, FastifyRequest } from "fastify";
import { config } from "./config.js";
import { db } from "./db.js";
import { FolderRow, ModelRow } from "./types.js";

export type PermissionPayload = {
  read: boolean;
  write: boolean;
};

export function canWriteLibrary(user: FastifyRequest["userInfo"], libraryType: "system" | "user", ownerUserId: number | null) {
  if (user.role === "admin") return true;
  if (libraryType === "user" && ownerUserId === user.id) return true;
  if (libraryType === "system" && config.allowUserEditSystemLibrary) return true;
  return false;
}

export function folderPermissions(user: FastifyRequest["userInfo"], folder: Pick<FolderRow, "library_type" | "owner_user_id">): PermissionPayload {
  return {
    read: true,
    write: canWriteLibrary(user, folder.library_type, folder.owner_user_id)
  };
}

export function modelPermissions(user: FastifyRequest["userInfo"], model: Pick<ModelRow, "library_type" | "owner_user_id">): PermissionPayload {
  return {
    read: true,
    write: canWriteLibrary(user, model.library_type, model.owner_user_id)
  };
}

export function getFolder(id: number) {
  return db.prepare(`
    SELECT f.*, u.username AS owner_username
    FROM folders f
    LEFT JOIN users u ON u.id = f.owner_user_id
    WHERE f.id = ?
  `).get(id) as FolderRow | undefined;
}

export function requireFolderWrite(request: FastifyRequest, reply: FastifyReply, folder: FolderRow) {
  if (!folderPermissions(request.userInfo, folder).write) {
    reply.code(403).send({ message: "没有该模型库的操作权限" });
    return false;
  }
  return true;
}

export function requireModelWrite(request: FastifyRequest, reply: FastifyReply, model: ModelRow) {
  if (!modelPermissions(request.userInfo, model).write) {
    reply.code(403).send({ message: "没有该模型的操作权限" });
    return false;
  }
  return true;
}
