import type { Service, CreateService } from './types.js';
import { getContainer } from '../../lib/cosmos-init.js';
import { productId } from '../../lib/config.js';

function getServicesContainer() {
  return getContainer('services');
}

export async function getAllServices(): Promise<Service[]> {
  const container = getServicesContainer();
  const { resources } = await container.items
    .query({
      query: 'SELECT * FROM c WHERE c.productId = @productId',
      parameters: [{ name: '@productId', value: productId }],
    })
    .fetchAll();

  return resources as Service[];
}

export async function getServiceById(id: string): Promise<Service | null> {
  try {
    const container = getServicesContainer();
    const { resource } = await container.item(id, id).read();
    return resource as Service;
  } catch {
    return null;
  }
}

export async function createService(data: CreateService): Promise<Service> {
  const container = getServicesContainer();
  const service: Service = {
    id: data.id || crypto.randomUUID(),
    name: data.name,
    scriptPath: data.scriptPath,
    healthUrl: data.healthUrl,
    repoPath: data.repoPath,
    status: 'down',
    version: 'unknown',
    productId,
  };

  const { resource } = await container.items.create(service);
  return resource as Service;
}

export async function updateService(id: string, updates: Partial<Service>): Promise<Service | null> {
  try {
    const container = getServicesContainer();
    const { resource } = await container.item(id, id).read();
    const updated = { ...resource, ...updates };
    const { resource: updatedResource } = await container.item(id, id).replace(updated);
    return updatedResource as Service;
  } catch {
    return null;
  }
}

export async function deleteService(id: string): Promise<boolean> {
  try {
    const container = getServicesContainer();
    await container.item(id, id).delete();
    return true;
  } catch {
    return false;
  }
}
