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

function getDeploymentsContainer() {
  return getContainer('deployments');
}

export async function getDeploymentsByService(serviceId: string, limit = 50): Promise<Deployment[]> {
  const container = getDeploymentsContainer();
  const { resources } = await container.items
    .query({
      query: 'SELECT * FROM c WHERE c.serviceId = @serviceId AND c.productId = @productId ORDER BY c.triggeredAt DESC OFFSET 0 LIMIT @limit',
      parameters: [
        { name: '@serviceId', value: serviceId },
        { name: '@productId', value: productId },
        { name: '@limit', value: limit },
      ],
    })
    .fetchAll();

  return resources as Deployment[];
}

export async function getRecentDeployments(limit = 20): Promise<Deployment[]> {
  const container = getDeploymentsContainer();
  const { resources } = await container.items
    .query({
      query: 'SELECT * FROM c WHERE c.productId = @productId ORDER BY c.triggeredAt DESC OFFSET 0 LIMIT @limit',
      parameters: [
        { name: '@productId', value: productId },
        { name: '@limit', value: limit },
      ],
    })
    .fetchAll();

  return resources as Deployment[];
}

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

export async function createDeployment(data: CreateDeployment): Promise<Deployment> {
  const container = getDeploymentsContainer();
  const deployment: Deployment = {
    id: data.id || crypto.randomUUID(),
    serviceId: data.serviceId,
    version: data.version || 'unknown',
    status: 'running',
    logs: '',
    triggeredBy: data.triggeredBy,
    triggeredAt: new Date().toISOString(),
    productId,
  };

  const { resource } = await container.items.create(deployment);
  return resource as Deployment;
}

export async function updateDeployment(id: string, updates: Partial<Deployment>): Promise<Deployment | null> {
  try {
    const container = getDeploymentsContainer();
    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 Deployment;
  } catch {
    return null;
  }
}
