/**
 * Clear Form 16 and demo request data for a full live test.
 * Deletes only DATA (rows). Does NOT drop tables or columns. Does NOT touch users table.
 *
 * Removes:
 * - All Form 16 submissions, credit notes, debit notes, and their FORM_16 workflow requests + related rows
 * - All demo CUSTOM requests (title like '[Demo]%') and their related rows
 *
 * Usage: npm run clear:form16-and-demo
 */

import { sequelize } from '../config/database';
import { QueryTypes } from 'sequelize';
import logger from '../utils/logger';

async function clearForm16AndDemoData(): Promise<void> {
  const transaction = await sequelize.transaction();

  try {
    logger.info('[Clear] Starting Form 16 and demo data cleanup (data only; users and schema untouched)...');

    // 1) Get request IDs to clear: FORM_16 and [Demo] CUSTOM
    const form16Rows = await sequelize.query<{ request_id: string }>(
      `SELECT request_id FROM workflow_requests WHERE template_type = 'FORM_16'`,
      { type: QueryTypes.SELECT, transaction }
    );
    const demoRows = await sequelize.query<{ request_id: string }>(
      `SELECT request_id FROM workflow_requests WHERE title LIKE '[Demo]%'`,
      { type: QueryTypes.SELECT, transaction }
    );
    const form16Ids = form16Rows.map((r) => r.request_id);
    const demoIds = demoRows.map((r) => r.request_id);
    const allRequestIds = [...new Set([...form16Ids, ...demoIds])];

    if (allRequestIds.length === 0) {
      logger.info('[Clear] No Form 16 or demo requests found. Nothing to delete.');
      await transaction.commit();
      return;
    }
    logger.info(`[Clear] Found ${form16Ids.length} Form 16 request(s) and ${demoIds.length} demo request(s) to clear.`);

    const reqPlaceholders = allRequestIds.map(() => '?').join(',');

    const deleteByRequestIds = async (table: string, col = 'request_id'): Promise<void> => {
      await sequelize.query(
        `DELETE FROM ${table} WHERE ${col} = ANY(ARRAY[${allRequestIds.map(() => '?').join(',')}]::uuid[])`,
        {
          replacements: allRequestIds,
          type: QueryTypes.DELETE,
          transaction,
        }
      );
    };

    // 2) Form 16–specific tables (all rows; no request_id filter)
    logger.info('[Clear] Deleting from form_16_debit_notes...');
    await sequelize.query(`DELETE FROM form_16_debit_notes`, { type: QueryTypes.DELETE, transaction });

    logger.info('[Clear] Deleting from form_16_credit_notes...');
    await sequelize.query(`DELETE FROM form_16_credit_notes`, { type: QueryTypes.DELETE, transaction });

    logger.info('[Clear] Deleting from form16a_submissions...');
    await sequelize.query(`DELETE FROM form16a_submissions`, { type: QueryTypes.DELETE, transaction });

    // 3) Workflow child tables: delete by request_id (Form 16 + demo)
    // shared_summaries: delete where summary_id in (select from request_summaries where request_id in ...)
    const summaryRows = await sequelize.query<{ summary_id: string }>(
      `SELECT summary_id FROM request_summaries WHERE request_id = ANY(ARRAY[${allRequestIds.map(() => '?').join(',')}]::uuid[])`,
      { replacements: allRequestIds, type: QueryTypes.SELECT, transaction }
    );
    const sidList = summaryRows.map((r) => r.summary_id);
    if (sidList.length > 0) {
      logger.info('[Clear] Deleting from shared_summaries...');
      await sequelize.query(
        `DELETE FROM shared_summaries WHERE summary_id = ANY(ARRAY[${sidList.map(() => '?').join(',')}]::uuid[])`,
        { replacements: sidList, type: QueryTypes.DELETE, transaction }
      );
    }

    // work_note_attachments: note_id in (work_notes for these request_ids)
    const noteRows = await sequelize.query<{ note_id: string }>(
      `SELECT note_id FROM work_notes WHERE request_id = ANY(ARRAY[${allRequestIds.map(() => '?').join(',')}]::uuid[])`,
      { replacements: allRequestIds, type: QueryTypes.SELECT, transaction }
    );
    const nidList = noteRows.map((r) => r.note_id);
    if (nidList.length > 0) {
      logger.info('[Clear] Deleting from work_note_attachments...');
      await sequelize.query(
        `DELETE FROM work_note_attachments WHERE note_id = ANY(ARRAY[${nidList.map(() => '?').join(',')}]::uuid[])`,
        { replacements: nidList, type: QueryTypes.DELETE, transaction }
      );
    }

    logger.info('[Clear] Deleting from work_notes...');
    await deleteByRequestIds('work_notes');

    logger.info('[Clear] Deleting from documents...');
    await deleteByRequestIds('documents');

    logger.info('[Clear] Deleting from activities...');
    await deleteByRequestIds('activities');

    logger.info('[Clear] Deleting from participants...');
    await deleteByRequestIds('participants');

    logger.info('[Clear] Deleting from approval_levels...');
    await deleteByRequestIds('approval_levels');

    logger.info('[Clear] Deleting from notifications...');
    await deleteByRequestIds('notifications');

    logger.info('[Clear] Deleting from request_summaries...');
    await deleteByRequestIds('request_summaries');

    logger.info('[Clear] Deleting from conclusion_remarks...');
    await deleteByRequestIds('conclusion_remarks');

    logger.info('[Clear] Deleting from tat_alerts...');
    await deleteByRequestIds('tat_alerts');

    logger.info('[Clear] Deleting from workflow_requests...');
    await deleteByRequestIds('workflow_requests');

    await transaction.commit();
    logger.info('[Clear] Done. Form 16 and demo request data cleared. Users table and all table structures unchanged.');
  } catch (error) {
    await transaction.rollback();
    logger.error('[Clear] Error:', error);
    throw error;
  }
}

if (require.main === module) {
  clearForm16AndDemoData()
    .then(() => {
      logger.info('[Clear] Exiting successfully.');
      process.exit(0);
    })
    .catch((err) => {
      logger.error('[Clear] Exiting with error.', err);
      process.exit(1);
    });
}

export { clearForm16AndDemoData };
