import 'dotenv/config';
import db from '../src/database/models/index.js';

const { StageApprovalPolicy } = db;

const policies = [
  {
    stageCode: 'INTERVIEW_LEVEL_1',
    minApprovals: 2,
    approvalMode: 'ROLE_MANDATORY',
    requiredRoles: ['DD-ZM', 'RBM'],
    isActive: true
  },
  {
    stageCode: 'INTERVIEW_LEVEL_2',
    minApprovals: 2,
    approvalMode: 'ROLE_MANDATORY',
    requiredRoles: ['ZBH', 'DD Lead'],
    isActive: true
  },
  {
    stageCode: 'INTERVIEW_LEVEL_3',
    minApprovals: 2,
    approvalMode: 'ROLE_MANDATORY',
    requiredRoles: ['NBH', 'DD Head'],
    isActive: true
  },
  {
    stageCode: 'LOI_APPROVAL',
    minApprovals: 2,
    approvalMode: 'ROLE_MANDATORY',
    requiredRoles: ['DD Head', 'NBH'],
    isActive: true
  },
  {
    stageCode: 'LOA_APPROVAL',
    minApprovals: 2,
    approvalMode: 'ROLE_MANDATORY',
    requiredRoles: ['DD Head', 'NBH'],
    isActive: true
  },
  {
    stageCode: 'FDD_VERIFICATION',
    minApprovals: 1,
    approvalMode: 'ROLE_MANDATORY',
    requiredRoles: ['DD Admin', 'Super Admin', 'DD Lead', 'DD Head'],
    isActive: true
  },
  {
    stageCode: 'CONSTITUTIONAL_ZM_RBM_REVIEW',
    minApprovals: 2,
    approvalMode: 'ROLE_MANDATORY',
    requiredRoles: ['DD-ZM', 'RBM'],
    isActive: true
  }
];

async function seedApprovalPolicies() {
  console.log('--- Seeding Approval Policies ---');

  for (const policy of policies) {
    const [record, created] = await StageApprovalPolicy.findOrCreate({
      where: { stageCode: policy.stageCode },
      defaults: policy
    });

    if (!created) {
      await record.update({
        minApprovals: policy.minApprovals,
        approvalMode: policy.approvalMode,
        requiredRoles: policy.requiredRoles,
        isActive: policy.isActive
      });
      console.log(`Updated policy: ${policy.stageCode}`);
    } else {
      console.log(`Created policy: ${policy.stageCode}`);
    }
  }

  console.log('--- Approval Policies Seeded ---');
}

seedApprovalPolicies()
  .catch((error) => {
    console.error('Approval policy seed failed:', error);
    process.exit(1);
  })
  .then(() => process.exit(0));
