import { db } from '../config/database.js';
import { serviceFolders, serviceDocuments, users } from '../db/schema.js';
import { desc, eq, sql } from 'drizzle-orm';
import { NotFoundError } from '../utils/errors.js';

/**
 * Get all service folders with document counts
 */
export const getAllFolders = async () => {
  const folders = await db
    .select({
      id: serviceFolders.id,
      name: serviceFolders.name,
      createdAt: serviceFolders.createdAt,
      updatedAt: serviceFolders.updatedAt,
      createdBy: serviceFolders.createdBy,
      creatorUsername: users.username,
      creatorFirstName: users.firstName,
      documentCount: sql`(SELECT COUNT(*) FROM service_documents WHERE folder_id = ${serviceFolders.id})::int`,
    })
    .from(serviceFolders)
    .leftJoin(users, eq(serviceFolders.createdBy, users.id))
    .orderBy(desc(serviceFolders.createdAt));

  return folders;
};

/**
 * Get folder by ID
 */
export const getFolderById = async (folderId) => {
  const [folder] = await db
    .select({
      id: serviceFolders.id,
      name: serviceFolders.name,
      createdAt: serviceFolders.createdAt,
      updatedAt: serviceFolders.updatedAt,
      createdBy: serviceFolders.createdBy,
      creatorUsername: users.username,
      creatorFirstName: users.firstName,
    })
    .from(serviceFolders)
    .leftJoin(users, eq(serviceFolders.createdBy, users.id))
    .where(eq(serviceFolders.id, folderId))
    .limit(1);

  if (!folder) {
    throw new NotFoundError('Priečinok nenájdený');
  }

  return folder;
};

/**
 * Create a new folder
 */
export const createFolder = async ({ name, userId }) => {
  const [newFolder] = await db
    .insert(serviceFolders)
    .values({
      name,
      createdBy: userId,
    })
    .returning();

  return newFolder;
};

/**
 * Update folder name
 */
export const updateFolder = async (folderId, { name }) => {
  const [existing] = await db
    .select()
    .from(serviceFolders)
    .where(eq(serviceFolders.id, folderId))
    .limit(1);

  if (!existing) {
    throw new NotFoundError('Priečinok nenájdený');
  }

  const [updated] = await db
    .update(serviceFolders)
    .set({
      name,
      updatedAt: new Date(),
    })
    .where(eq(serviceFolders.id, folderId))
    .returning();

  return updated;
};

/**
 * Delete a folder (cascade deletes documents)
 */
export const deleteFolder = async (folderId) => {
  const [existing] = await db
    .select()
    .from(serviceFolders)
    .where(eq(serviceFolders.id, folderId))
    .limit(1);

  if (!existing) {
    throw new NotFoundError('Priečinok nenájdený');
  }

  await db.delete(serviceFolders).where(eq(serviceFolders.id, folderId));

  return { success: true, message: 'Priečinok bol odstránený' };
};
