import { getCollection } from '../../lib/datastore.js';
import type { MaintenanceConfig, MaintenanceWindow } from './types.js';

// ── Maintenance Config ───────────────────────────────────────
// Stored as a single document per product in the settings container.
// Uses the existing settings container (no new container needed).

interface MaintenanceSettingsDoc {
  id: string;
  productId: string;
  type: 'maintenance_config';
  config: MaintenanceConfig;
  _ts?: number;
  _etag?: string;
}

function settingsCollection() {
  return getCollection<MaintenanceSettingsDoc>('settings', '/productId');
}

const DEFAULT_CONFIG: MaintenanceConfig = {
  mode: 'off',
  message: '',
  bypassRoles: ['super_admin', 'admin'],
  bypassIPs: [],
  affectedServices: ['*'],
  updatedAt: new Date().toISOString(),
  updatedBy: 'system',
};

function docId(productId: string): string {
  return `maintenance_${productId}`;
}

export async function getMaintenanceConfig(productId: string): Promise<MaintenanceConfig> {
  try {
    const doc = await settingsCollection().findById(docId(productId), productId);
    return doc?.config ?? DEFAULT_CONFIG;
  } catch {
    return DEFAULT_CONFIG;
  }
}

export async function updateMaintenanceConfig(
  productId: string,
  config: MaintenanceConfig
): Promise<MaintenanceConfig> {
  const id = docId(productId);
  const doc: MaintenanceSettingsDoc = {
    id,
    productId,
    type: 'maintenance_config',
    config,
  };

  const result = await settingsCollection().upsert(doc);
  return result.config;
}

// ── Maintenance Windows ──────────────────────────────────────

function windowsCollection() {
  return getCollection<MaintenanceWindow>('maintenance_windows', '/productId');
}

export async function listUpcomingWindows(productId: string): Promise<MaintenanceWindow[]> {
  const now = new Date().toISOString();
  // Fetch all for this product and filter in-memory for scheduledEnd > now
  const all = await windowsCollection().findMany({
    filter: { productId },
    sort: { scheduledStart: 1 },
  });
  return all.filter(w => w.scheduledEnd > now);
}

export async function createWindow(doc: MaintenanceWindow): Promise<MaintenanceWindow> {
  return windowsCollection().create(doc);
}

export async function deleteWindow(id: string, productId: string): Promise<boolean> {
  try {
    await windowsCollection().delete(id, productId);
    return true;
  } catch {
    return false;
  }
}
