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

/**
 * Get all services
 */
export const getAllServices = async () => {
  return await db
    .select()
    .from(services)
    .orderBy(desc(services.createdAt));
};

/**
 * Get service by ID
 */
export const getServiceById = async (serviceId) => {
  const [service] = await db
    .select()
    .from(services)
    .where(eq(services.id, serviceId))
    .limit(1);

  if (!service) {
    throw new NotFoundError('Služba nenájdená');
  }

  return service;
};

/**
 * Create new service
 * @param {string} userId - ID of user creating the service
 * @param {object} data - Service data
 */
export const createService = async (userId, data) => {
  const { name, price, pricingTiers, description } = data;

  const [newService] = await db
    .insert(services)
    .values({
      name,
      price,
      pricingTiers: pricingTiers || null,
      description: description || null,
      createdBy: userId,
    })
    .returning();

  return newService;
};

/**
 * Update service
 * @param {string} serviceId - ID of service to update
 * @param {object} data - Updated data
 */
export const updateService = async (serviceId, data) => {
  const service = await getServiceById(serviceId);

  const { name, price, pricingTiers, description } = data;

  const [updated] = await db
    .update(services)
    .set({
      name: name !== undefined ? name : service.name,
      price: price !== undefined ? price : service.price,
      pricingTiers: pricingTiers !== undefined ? pricingTiers : service.pricingTiers,
      description: description !== undefined ? description : service.description,
      updatedAt: new Date(),
    })
    .where(eq(services.id, serviceId))
    .returning();

  return updated;
};

/**
 * Delete service
 */
export const deleteService = async (serviceId) => {
  await getServiceById(serviceId); // Check if exists

  await db.delete(services).where(eq(services.id, serviceId));

  return { success: true, message: 'Služba bola odstránená' };
};
