const { pool } = require('../src/config/database')
const GroupContact = require('../src/models/GroupContact')

const run = async () => {
  await GroupContact.ensureContactForeignKey()
  const [rows] = await pool.execute("SELECT REFERENCED_TABLE_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'group_contact_mappings' AND COLUMN_NAME = 'contact_id'")
  console.log('FK refs:', rows)

  const args = process.argv.slice(2)
  const insertIdx = args.indexOf('--insert')
  if (insertIdx !== -1 && args.length >= insertIdx + 4) {
    const orgId = Number(args[insertIdx + 1])
    const deptIdRaw = args[insertIdx + 2]
    const deptId = deptIdRaw === 'null' ? null : Number(deptIdRaw)
    const contactId = Number(args[insertIdx + 3])
    const affected = await GroupContact.forceInsert(orgId, deptId, contactId)
    console.log('forceInsert affectedRows:', affected)
    const [checkRows] = await pool.execute("SELECT id, organization_id, department_id, contact_id, created_at FROM group_contact_mappings WHERE contact_id = ? ORDER BY id DESC LIMIT 10", [contactId])
    console.log('Mappings for contact_id', contactId, checkRows)
  }
  await pool.end()
}

run().then(() => process.exit(0)).catch(err => { console.error(err); process.exit(1) })
