import { fetch } from "pouchdb-fetch";

const dbsSecurity = {
  _users: {
    admins: { roles: ["_admin"] },
    members: { roles: ["_admin"] },
  },
  _replicator: {
    admins: { roles: ["_admin"] },
    members: { roles: ["_admin"] },
  },
  _global_changes: {
    admins: { roles: ["_admin"] },
    members: { roles: ["_admin"] },
  },

  server_settings: {
    admins: { roles: ["_admin"] },
    members: { roles: ["_admin"] },
  },
  web_push_subscriptions: {
    admins: { roles: ["_admin"] },
    members: { roles: [] },
  },
  messages: {
    admins: { roles: ["_admin"] },
    members: { roles: [] },
  },
  qr: {
    admins: { roles: ["_admin"] },
    members: { roles: [] },
  },
  public_settings: {
    admins: { roles: ["_admin"] },
    members: { roles: [] },
  },
  user_chat_settings: {
    admins: { roles: ["_admin"] },
    members: { roles: [] },
  },
};

export const up = async () => {
  for (const [dbName, dbSecurity] of Object.entries(dbsSecurity)) {
    const responseCreateDb = await fetch(`${process.env.API_URL}/${dbName}`, {
      method: "PUT",
    }).then((response) => response.json());

    console.assert(
      responseCreateDb.ok,
      `${dbName} create db error ${JSON.stringify(responseCreateDb)}`,
    );

    const responseSetSecurity = await fetch(`${process.env.API_URL}/${dbName}/_security`, {
        method: "PUT",
        body: JSON.stringify(dbSecurity),
     }).then((response) => response.json());

    console.assert(
      responseSetSecurity.ok,
      `${dbName} security error  ${JSON.stringify(responseSetSecurity)}`,
    );
  }
};

export const down = async () => {
  for (const dbName of Object.keys(dbsSecurity)) {
    const responseDeleteDb = await fetch(`${process.env.API_URL}/${dbName}`, {
      method: "DELETE",
    });
    console.assert(
      (await responseDeleteDb.json()).ok,
      `${dbName} create db error`,
    );
  }
};
