/**
 * superadmin.routes.js
 */

const express = require('express');
const crypto = require('crypto');
const router = express.Router();
const controller = require('../controllers/superadmin.controller');
const { superAdminAuth } = require('../middleware/superAdminAuth');
const LicenseTokenGenerator = require('../services/LicenseTokenGenerator');
const SupabaseSuperAdminService = require('../services/SupabaseSuperAdminService');
const SuperAdminConfigService = require('../services/SuperAdminConfigService');
// Public auth
router.post('/auth/login', controller.login);

const { publicKey: jwksPublicKey } = LicenseTokenGenerator.getKeyPair();
const jwksDer = Buffer.from(
  jwksPublicKey
    .replace(/-----BEGIN PUBLIC KEY-----/g, '')
    .replace(/-----END PUBLIC KEY-----/g, '')
    .replace(/\s+/g, ''),
  'base64'
);
const jwksKid = crypto.createHash('sha256').update(jwksDer).digest('hex').slice(0, 16);

router.get('/v1/auth/jwks', (req, res) => {
  res.json({
    keys: [
      {
        kty: 'OKP',
        crv: 'Ed25519',
        use: 'sig',
        alg: 'EdDSA',
        kid: jwksKid,
        pubKeyPem: jwksPublicKey
      }
    ]
  });
});

// Protected SuperAdmin Endpoints
router.get('/metrics', superAdminAuth, controller.getMetrics);
router.get('/tenants', superAdminAuth, controller.listTenants);
router.post('/tenants', superAdminAuth, controller.createTenant);
router.put('/tenants/:id', superAdminAuth, controller.updateTenant);
// Licensing & Overrides
router.post('/tenants/:id/licenses', superAdminAuth, controller.issueLicense);
router.get('/tenants/:id/licenses/download', superAdminAuth, controller.downloadLicenseArtifact);
router.get('/tenants/:id/licenses/:licId/download', superAdminAuth, controller.downloadLicenseArtifact);
router.get('/tenants/:id/licenses/cloud', superAdminAuth, controller.getCloudLicenseForTenant);
router.post('/tenants/:id/licenses/repush', superAdminAuth, controller.repushLicenseToSupabase);
router.post('/tenants/:id/override', superAdminAuth, controller.grantOverride);
// Supabase Cloud Inspection & Reissue / Repush
router.get('/tenants/:id/supabase', superAdminAuth, controller.inspectTenantSupabase);
router.post('/tenants/:id/supabase/repush', superAdminAuth, controller.repushTenantSupabase);
router.post('/tenants/:id/supabase/reissue', superAdminAuth, controller.repushTenantSupabase);

// Multi-School Instance Orchestrator (Spawning server/client school instances)
router.get('/instances', superAdminAuth, controller.listInstances);
router.post('/instances/spawn', superAdminAuth, controller.spawnInstance);
router.post('/instances/:id/stop', superAdminAuth, controller.stopInstance);
router.post('/instances/:id/start', superAdminAuth, controller.startInstance);
router.post('/instances/:id/restart', superAdminAuth, controller.restartInstance);
router.get('/instances/:id/logs', superAdminAuth, controller.getInstanceLogs);

router.get('/supabase/config', superAdminAuth, async (req, res) => {
  try {
    const status = await SupabaseSuperAdminService.getStatus();
    return res.json({
      ok: true,
      configured: status.configured,
      hasUrl: status.hasUrl,
      hasKey: status.hasKey,
      keySource: status.keySource,
      canConnect: status.canConnect
    });
  } catch (err) {
    return res.status(500).json({ ok: false, error: err.message });
  }
});

// POST /api/supabase/config and DELETE /api/supabase/config are
// intentionally removed. The SuperAdmin UI no longer accepts API
// keys; operators set SUPABASE_URL and SUPABASE_KEY (or
// VITE_SUPABASE_ANON_KEY) in `superadmin/server/.env` and restart
// the process. Writes go through SECURITY DEFINER RPC functions
// (upsert_tenant_cloud, upsert_license_cloud) — the service-role
// key is never used. See SUPERADMIN_MULTITENANT_DOCUMENTATION.md §2.1.

router.get('/supabase/tenants', superAdminAuth, async (req, res) => {
  try {
    if (!SupabaseSuperAdminService.isConfigured()) {
      return res.status(503).json({ ok: false, error: 'Supabase client not configured' });
    }
    const data = await SupabaseSuperAdminService.fetchCloudTenants();
    return res.json({ ok: true, count: data.length, data });
  } catch (err) {
    return res.status(500).json({ ok: false, error: err.message });
  }
});

router.get('/supabase/licenses', superAdminAuth, async (req, res) => {
  try {
    if (!SupabaseSuperAdminService.isConfigured()) {
      return res.status(503).json({ ok: false, error: 'Supabase client not configured' });
    }
    const data = await SupabaseSuperAdminService.fetchCloudLicenses();
    return res.json({ ok: true, count: data.length, data });
  } catch (err) {
    return res.status(500).json({ ok: false, error: err.message });
  }
});

router.get('/supabase/tenants/:id', superAdminAuth, async (req, res) => {
  try {
    if (!SupabaseSuperAdminService.isConfigured()) {
      return res.status(503).json({ ok: false, error: 'Supabase client not configured' });
    }
    const data = await SupabaseSuperAdminService.fetchCloudTenantById(req.params.id);
    if (!data) {
      return res.status(404).json({ ok: false, error: 'Tenant not found in cloud' });
    }
    return res.json({ ok: true, data });
  } catch (err) {
    return res.status(500).json({ ok: false, error: err.message });
  }
});

router.get('/supabase/licenses/by-tenant/:tenantId', superAdminAuth, async (req, res) => {
  try {
    if (!SupabaseSuperAdminService.isConfigured()) {
      return res.status(503).json({ ok: false, error: 'Supabase client not configured' });
    }
    const data = await SupabaseSuperAdminService.fetchCloudLicensesForTenant(req.params.tenantId);
    return res.json({ ok: true, count: data.length, data });
  } catch (err) {
    return res.status(500).json({ ok: false, error: err.message });
  }
});

router.post('/supabase/sync/pull', superAdminAuth, async (req, res) => {
  try {
    const report = await SupabaseSuperAdminService.pullAndReconcile();
    return res.json(report);
  } catch (err) {
    return res.status(500).json({ ok: false, error: err.message });
  }
});

module.exports = router;
