import { google } from "googleapis";

/* Change this import statement to point to the credentials JSON file */
import creds from './sheetjs-test-726272627262.json' assert { type: "json" };

/* Change this to the primary account address, NOT THE SERVICE ACCOUNT */
const acct = "YOUR_ADDRESS@gmail.com";

/* connect to google services */
const jwt = new google.auth.JWT({
  email: creds.client_email,
  key: creds.private_key,
  scopes: [
    'https://www.googleapis.com/auth/spreadsheets',
    'https://www.googleapis.com/auth/drive.file',
  ]
});

const sheets = google.sheets({ version: "v4", auth: jwt });
const drive = google.drive({version: "v3", auth: jwt });

/* create new google workbook */
const [id, sheet0id] = await (async() => {
  const res = await sheets.spreadsheets.create({
    requestBody: {
      properties: {
        title: "SheetJS Test"
      }
    }
  });
  const id = res.data.spreadsheetId;
  const sheet0id = res.data.sheets[0].properties.sheetId;
  return [id, sheet0id];
})();
console.log(`Created Google Workbook ${id}`);

/* create new google worksheet and delete initial sheet */
const [sheet1id, sheet2id] = await (async() => {
  const res = await sheets.spreadsheets.batchUpdate({
    spreadsheetId: id,
    requestBody: { requests: [
      /* add SheetJS1 */
      { addSheet: { properties: { title: "SheetJS1" } } },
      /* add SheetJS2 */
      { addSheet: { properties: { title: "SheetJS2" } } },
      /* remove default sheet */
      { deleteSheet: { sheetId: sheet0id } },
    ] }
  });
  console.log(`Created Google Worksheets "SheetJS1" and "SheetJS2"`);
  return res.data.replies.slice(0,2).map(r => r.addSheet.properties.sheetId);
})();

await sheets.spreadsheets.values.update({
  spreadsheetId: id,
  range: "SheetJS1!A1",
  valueInputOption: "USER_ENTERED",
  resource: { values: [
    ["Sheet", "JS"],
    [72, 62]
  ]}
});

await sheets.spreadsheets.values.update({
  spreadsheetId: id,
  range: "SheetJS2!A1",
  valueInputOption: "USER_ENTERED",
  resource: { values: [
    ["Area Code", "Part 1", "Part 2"],
    [201, 867, 5309],
    [281, 330, 8004],
  ]}
});

/* Share new Document with the primary account */
try {
  await drive.permissions.create({
    fileId: id,
    fields: "id",
    requestBody: {
      type: "user",
      role: "writer",
      emailAddress: acct
    }
  });
  console.log(`Shared ${id} with ${acct}`);
} catch(e) { console.log(e); }