import { createAction, OAuth2PropertyValue } from '@activepieces/pieces-framework';
import { excelAuth } from '../auth';
import { commonProps } from '../common/props';
import { getDrivePath, createMSGraphClient } from '../common/helpers';

export const deleteTableAction = createAction({
  auth: excelAuth,
  name: 'delete_table',
  description: 'Delete a table from a worksheet',
  audience: 'both',
  aiMetadata: { description: 'Delete a defined Excel table (by table id) from a worksheet, removing the table object while leaving the underlying cell values in place. Use to drop table formatting/structure, not to clear data. Idempotent in effect — once the table is gone, re-running on the same id targets a non-existent table.', idempotent: true },
  displayName: 'Delete Table',
  props: {
    storageSource: commonProps.storageSource,
    siteId: commonProps.siteId,
    documentId: commonProps.documentId,
    workbookId: commonProps.workbookId,
    worksheetId: commonProps.worksheetId,
    tableId: commonProps.tableId,
  },
  async run({ propsValue, auth }) {
    const { storageSource, siteId, documentId, workbookId, worksheetId, tableId } = propsValue;
    const cloud = (auth as OAuth2PropertyValue).props?.['cloud'] as string | undefined;

    if (storageSource === 'sharepoint' && (!siteId || !documentId)) {
      throw new Error('please select SharePoint site and document library.');
    }
    const drivePath = getDrivePath(storageSource, siteId as string, documentId as string);

    const client = createMSGraphClient(auth['access_token'], cloud);
    await client.api(`${drivePath}/items/${workbookId}/workbook/worksheets/${worksheetId}/tables/${tableId}`).delete();
    return { success: true };
  },
});
