import { graphConnectionSchema } from '../forms/schemas.js';
import { createGraphConnection, deleteGraphConnection, getGraphConnection, listGraphConnections, recordGraphConnectionTest, updateGraphConnection } from '../models/graphModel.js';
import { listGraphMobileApps, testGraphConnection } from '../services/graphService.js';

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

// Governance flags (tenant write-back, approval requirement) are administrative.
// On create, non-admins always get read-only. On update, non-admins keep the
// existing flag values so they can never grant or silently downgrade them.
export function create(req, res) {
  const parsed = graphConnectionSchema.safeParse(req.body);
  if (!parsed.success || !parsed.data.clientSecret) return res.status(400).json({ error: 'Valid Graph connection payload with client secret is required' });
  if (req.user.role !== 'admin') {
    parsed.data.allowWrite = false;
    parsed.data.requireApproval = false;
    parsed.data.publisherIds = [];
    parsed.data.approverIds = [];
  }
  res.status(201).json(createGraphConnection(parsed.data, req.user.id));
}

export function update(req, res) {
  const parsed = graphConnectionSchema.safeParse(req.body);
  if (!parsed.success) return res.status(400).json({ error: 'Invalid Graph connection payload' });
  if (req.user.role !== 'admin') {
    const existing = getGraphConnection(req.params.id, req.user.id);
    parsed.data.allowWrite = Boolean(existing?.allowWrite);
    parsed.data.requireApproval = Boolean(existing?.requireApproval);
    parsed.data.publisherIds = existing?.publisherIds || [];
    parsed.data.approverIds = existing?.approverIds || [];
  }
  const connection = updateGraphConnection(req.params.id, parsed.data, req.user.id);
  if (!connection) return res.status(404).json({ error: 'Graph connection not found' });
  res.json(connection);
}

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

export async function test(req, res) {
  const connection = getGraphConnection(req.params.id, req.user.id, true);
  if (!connection) return res.status(404).json({ error: 'Graph connection not found' });
  try {
    const result = await testGraphConnection(connection);
    recordGraphConnectionTest(req.params.id, 'success', result.message);
    res.json(result);
  } catch (error) {
    recordGraphConnectionTest(req.params.id, 'failed', error.message);
    res.status(400).json({ ok: false, error: error.message });
  }
}

export async function mobileApps(req, res) {
  const connection = getGraphConnection(req.params.id, req.user.id, true);
  if (!connection) return res.status(404).json({ error: 'Graph connection not found' });
  try {
    res.json(await listGraphMobileApps(connection, String(req.query.q || '')));
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
}
