const enums = require('../../enums');

function findOne() {
  return `SELECT * FROM "modules" WHERE "id" = ?`;
}

function createTable(name, fields) {
  let columns = fields.map(field => {
    let column = '';
    if (field.dataType === enums.dataType.integer) {
      column = `"${field.name}" integer `;
    } else if (field.dataType === enums.dataType.varchar) {
      column = `"${field.name}" character varying(255) COLLATE pg_catalog."default" `;
    } else if (field.dataType === enums.dataType.boolean) {
      column = `"${field.name}" boolean `;
    } else if (field.dataType === enums.dataType.text || field.dataType === enums.dataType.byte) {
      column = `"${field.name}" text `;
    } else if (field.dataType === enums.dataType.datetime) {
      column = `"${field.name}" timestamp with time zone NOT NULL DEFAULT now() `;
    } else if (field.dataType === enums.dataType.json) {
      column = `"${field.name}" jsonb `;
    }

    if (field.autoIncrement) {
      column += ` DEFAULT nextval('"${name}_${field.name}_seq"'::regclass) `;
    }

    if (field.notNull) {
      column += ' NOT NULL ';
    }

    if (field.defaultValue) {
      column += ` DEFAULT ${field.defaultValue} `;
    }

    return column;
  });

  columns.push(`"createdAt" timestamp with time zone NOT NULL DEFAULT now()`);
  columns.push(`"updatedAt" timestamp with time zone NOT NULL DEFAULT now()`);

  let primaryKey = fields.find(field => field.identity).name;
  let sequence = fields.find(field => field.autoIncrement).name;

  columns = columns.join(',');

  return `
    CREATE SEQUENCE "${name}_${sequence}_seq";
    CREATE TABLE IF NOT EXISTS public."${name}" (${columns}, PRIMARY KEY ("${primaryKey}"))
    TABLESPACE pg_default;
    ALTER TABLE IF EXISTS public."${name}" OWNER to postgres;
  `;
}

function deleteTable(name, sequence) {
  return `
    DROP TABLE IF EXISTS public."${name}";
    DROP SEQUENCE IF EXISTS "${name}_${sequence}_seq";
  `;
}

module.exports = {
  findOne,
  createTable,
  deleteTable,
};
