'use strict';

const { jsonResponse, readBody } = require('./api-utils');

function getScheduler() {
  const { Scheduler } = require('../lib/scheduler');
  return Scheduler.getInstance ? Scheduler.getInstance() : null;
}

function handleSchedulerApi(req, res, url) {
  const p = url.pathname;
  const m = req.method;

  if (p === '/api/wall-e/scheduler/jobs' && m === 'GET') {
    try {
      const sch = getScheduler();
      if (!sch) return jsonResponse(res, { jobs: [], overrides: {} });
      const jobs = sch.getJobs ? sch.getJobs() : [];
      const overrides = sch.getModelOverrides ? sch.getModelOverrides() : {};
      jsonResponse(res, { jobs, overrides });
    } catch (e) {
      jsonResponse(res, { error: e.message }, 500);
    }
    return true;
  }

  const schedulerModelMatch = p.match(/^\/api\/wall-e\/scheduler\/jobs\/([\w_-]+)\/model$/);
  if (schedulerModelMatch && m === 'POST') {
    const jobName = schedulerModelMatch[1];
    readBody(req).then((body) => {
      try {
        const sch = getScheduler();
        if (!sch) return jsonResponse(res, { error: 'Scheduler not available' }, 503);
        const override = body && Object.keys(body).length > 0 ? body : null;
        const updated = sch.setModelOverride(jobName, override);
        jsonResponse(res, { jobName, override: updated[jobName] || null, allOverrides: updated });
      } catch (e) {
        jsonResponse(res, { error: e.message }, 500);
      }
    });
    return true;
  }

  return false;
}

module.exports = {
  handleSchedulerApi,
};
