import { fetch } from "pouchdb-fetch";

const dbsSecurity = {
  web_push_subscriptions: {
    admins: { roles: ["_admin"] },
    members: { roles: [] },
  },
  messages: {
    admins: { roles: ["_admin"] },
    members: { roles: [] },
  },
  server_settings: {
    admins: { roles: ["_admin"] },
    members: { roles: ["_admin"] },
  },
  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",
    });
    console.assert(
      (await responseCreateDb.json()).ok,
      `${dbName} create db error`,
    );
    const responseSetSecurity = await fetch(
      `${process.env.API_URL}/${dbName}/_security`,
      {
        method: "PUT",
        body: JSON.stringify(dbSecurity),
      },
    );
    console.assert(
      (await responseSetSecurity.json()).ok,
      `${dbName} security error`,
    );
  }
};

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`,
    );
  }
};
