import pg from "../postgres.js";
// Imports
import {
  insertQuery,
  selectWhereAnyQuery,
  selectWhereAllQuery,
  updateWhereAnyQuery,
} from "../pg-query.js";
// Constants
const table = "test_results";
const PG_DISABLED = process.env.POSTGRES_DISABLED;

const failingMock = () => {
  return [
    {
      name: "failing",
      class: "failing.js",
      timestamp: new Date().toJSON(),
      method: "FAKEMETHOD",
      cron: "1hour",
      type: "api",
      dailyFails: 12,
      screenshot: "https://picsum.photos/1920/1080",
      recentResults: [1, 0, 0, 1, 0],
      isPipeline: false,
      failedMessage: `Some Test FailureMessage`,
    },
    {
      name: "secondary1",
      class: "secondary1.js",
      timestamp: new Date().toJSON(),
      method: "FAKEMETHOD",
      cron: "1hour",
      type: "api",
      dailyFails: 1,
      screenshot: "https://picsum.photos/1920/1080",
      recentResults: [1, 0, 0, 1, 0],
      isPipeline: true,
      failedMessage: `Some Test FailureMessage from Secondary1`,
    },
  ];
};
// Queries
export const insertTestResult = (testResult) => {
  const {
    test_name,
    test_class,
    test_method,
    test_path,
    test_type,
    test_timestamp,
    test_retry,
    origin,
    failed,
    failed_message,
    screenshot_url,
    expected_screenshot_url,
    weblog_url,
  } = testResult;

  var query = insertQuery(table, {
    test_name,
    test_class,
    test_method,
    test_path,
    test_type,
    test_timestamp,
    test_retry,
    origin,
    failed,
    failed_message,
    screenshot_url,
    expected_screenshot_url,
    weblog_url,
  });

  query += "\n RETURNING *";
  return pg.query(query);
};

export const getCurrentlyFailing = async () => {
  if (PG_DISABLED) return failingMock();
  /**/
  const query = `WITH recent as (SELECT * FROM test_results WHERE (timestamp BETWEEN NOW() - INTERVAL '24 HOURS' AND NOW()) AND NOT(failed AND retry)) SELECT * FROM recent WHERE timestamp = (SELECT MAX(timestamp) FROM recent r2 WHERE recent.name = r2.name) AND failed;
`;
  return pg.query(query);

  /*SELECT * FROM test_results WHERE "timestamp" BETWEEN NOW() - INTERVAL '24 HOURS' AND NOW(); <-- Last 24 hours all runs*/

  /* SELECT * FROM test_results tr1 WHERE timestamp BETWEEN NOW() - INTERVAL '24 HOURS' AND NOW() AND timestamp = (SELECT MAX(timestamp) FROM test_results tr2 WHERE tr1.name = tr2.name); <-- Last 24 hours only most recent
   */
};

export const getCurrentlyFailingFull = (env) => {
  const query = `WITH recent AS (SELECT * FROM test_results WHERE (timestamp BETWEEN NOW() - INTERVAL '24 HOURS' AND NOW()) AND NOT(failed AND retry) AND env='prod') SELECT * FROM recent INNER JOIN test_catalog USING(name) WHERE timestamp = (SELECT MAX(timestamp) FROM recent r2 WHERE recent.name = r2.name) AND failed;
;`;
  return pg.query(query);
};
