import { hostSchema, vcenterImportSchema, vcenterPreviewSchema } from '../forms/schemas.js';
import { createHost, deleteHost, findVisibleHostByIdentity, listHosts, updateHost } from '../models/hostModel.js';
import { buildHostPayloadFromVm, previewVCenterHosts, vcenterStatus } from '../services/vcenterService.js';

export function index(req, res) {
  res.json(listHosts(req.user.id));
}

export function create(req, res) {
  const parsed = hostSchema.safeParse(req.body);
  if (!parsed.success) return res.status(400).json({ error: 'Invalid host payload' });
  res.status(201).json(createHost(parsed.data, req.user.id));
}

export function update(req, res) {
  const host = updateHost(req.params.id, req.body, req.user.id);
  if (!host) return res.status(404).json({ error: 'Host not found' });
  res.json(host);
}

export function destroy(req, res) {
  deleteHost(req.params.id, req.user.id);
  res.status(204).end();
}

export function vcenterImportStatus(req, res) {
  res.json(vcenterStatus());
}

export async function previewVCenterImport(req, res) {
  const parsed = vcenterPreviewSchema.safeParse(req.body);
  if (!parsed.success) return res.status(400).json({ error: 'Invalid vCenter preview payload' });
  try {
    res.json(await previewVCenterHosts(parsed.data));
  } catch (err) {
    res.status(502).json({ error: err.message });
  }
}

export async function importVCenterHosts(req, res) {
  const parsed = vcenterImportSchema.safeParse(req.body);
  if (!parsed.success) return res.status(400).json({ error: 'Invalid vCenter import payload' });
  try {
    const preview = await previewVCenterHosts(parsed.data);
    const selected = new Set(parsed.data.vmIds || []);
    const candidates = selected.size
      ? preview.candidates.filter((candidate) => selected.has(candidate.id))
      : preview.candidates;
    const imported = [];
    const skipped = [];

    for (const candidate of candidates) {
      const hostPayload = buildHostPayloadFromVm(candidate, parsed.data);
      const existing = findVisibleHostByIdentity(hostPayload, req.user.id);
      if (existing) {
        skipped.push({ vm: candidate, reason: `Existing host matched ${existing.name}` });
        continue;
      }
      imported.push(createHost(hostPayload, req.user.id));
    }

    res.status(201).json({ imported, skipped, scanned: preview.count });
  } catch (err) {
    res.status(502).json({ error: err.message });
  }
}
