import type { BoardItem } from '@/types';
import { doc, Timestamp, setDoc, updateDoc } from 'firebase/firestore';

export const getBoardDocRef = (currentCollection: any) => {
  const docRef = doc(currentCollection);
  return {
    docId: docRef.id,
    docRef,
  };
};

// Create new BoardItem with timestamp and boards_number
export const createBoardsData = (
  base: BoardItem,
  newBoardsNumber: number
): BoardItem => ({
  ...base,
  boards_number: base.boards_number || newBoardsNumber,
  created: base.created || Timestamp.now(),
});
// For Create
export const handleCreateBoard = async (
  board: BoardItem,
  currentCollection: any
) => {
  const docRef = doc(currentCollection);
  board.docId = docRef.id;

  console.log(
    `[handleCreateBoard] Creating new board document with ID: ${board.docId}`
  );
  await setDoc(docRef, board);
  console.log(`[handleCreateBoard] Board created successfully`);

  return docRef.id;
};

// For Update
export const handleUpdateBoard = async (
  board: BoardItem,
  currentCollection: any
) => {
  console.log(
    `[handleUpdateBoard] Updating board document with ID: ${board.docId}`
  );
  await setDoc(doc(currentCollection, board.docId), board, { merge: true });
  console.log(`[handleUpdateBoard] Board updated successfully`);
};
