#!/usr/bin/env bash
# Populate NexusCRM with realistic test data across all available CRM objects.
# Idempotent: safe to re-run — creates objects if missing, then populates records.
#
# Usage:
#   ./scripts/populate_test_data.sh
#   API_BASE_URL=http://127.0.0.1:43001 FRONTEND_URL=http://127.0.0.1:4173 ./scripts/populate_test_data.sh

set -euo pipefail

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
source "${PROJECT_ROOT}/scripts/runtime-env.sh"
nexus_export_runtime_env "${PROJECT_ROOT}"

BASE_URL="${BASE_URL:-${API_BASE_URL}}"
EMAIL="${EMAIL:-admin@test.com}"
PASSWORD="${PASSWORD:-${NEXUS_ADMIN_PASSWORD:-}}"
if [ -z "${PASSWORD:-}" ]; then
  echo "❌ PASSWORD or NEXUS_ADMIN_PASSWORD env var is required. Export it before running this script." >&2
  exit 1
fi
API="$BASE_URL/services/data/v63.0"
FRONTEND_ORIGIN="${FRONTEND_ORIGIN:-${FRONTEND_URL}}"

ADMIN_ID="10000000-0000-0000-0000-000000000001"
SALES_ID="10000000-0000-0000-0000-000000000002"
DEAL_ID="10000000-0000-0000-0000-000000000003"
LEGAL_ID="10000000-0000-0000-0000-000000000004"

echo "🔐 Authenticating as $EMAIL..."
TOKEN=$(curl -sf -X POST "$BASE_URL/services/oauth2/token" \
  --data-urlencode "grant_type=password" \
  --data-urlencode "username=${EMAIL}" \
  --data-urlencode "password=${PASSWORD}" | python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])")

if [ -z "$TOKEN" ]; then
  echo "❌ Authentication failed"
  exit 1
fi
echo "✅ Authenticated"

AUTH="Authorization: Bearer $TOKEN"
CT="Content-Type: application/json"
ORIGIN="Origin: ${FRONTEND_ORIGIN}"

created=0
failed=0

api_post() {
  local path="$1"
  local data="$2"
  curl -s -X POST "${BASE_URL}${path}" -H "$AUTH" -H "$CT" -H "$ORIGIN" -d "$data"
}

ensure_object() {
  local name="$1" label="$2" plural="$3"
  local resp
  resp=$(api_post "/services/data/v63.0/tooling/sobjects/CustomObject" \
    "{\"name\":\"$name\",\"label\":\"$label\",\"labelPlural\":\"$plural\",\"custom\":false}")
  if echo "$resp" | python3 -c "import sys,json; d=json.load(sys.stdin); exit(0 if d.get('success') else 1)" 2>/dev/null; then
    echo "   ✅ Object: $name"
  else
    echo "   ⚠  Object $name: $resp"
  fi
}

ensure_field() {
  local obj="$1" field="$2" label="$3" ftype="$4"
  shift 4
  local extra="$*"
  local meta="{\"label\":\"$label\",\"type\":\"$ftype\"$extra}"
  local resp
  resp=$(api_post "/services/data/v63.0/tooling/sobjects/CustomField" \
    "{\"FullName\":\"$obj.$field\",\"TableEnumOrId\":\"$obj\",\"Metadata\":$meta}")
  if echo "$resp" | python3 -c "import sys,json; d=json.load(sys.stdin); exit(0 if d.get('success') else 1)" 2>/dev/null; then
    echo "   ✅ Field: $obj.$field"
  else
    echo "   ⚠  Field $obj.$field: $resp"
  fi
}

ensure_field_json() {
  local obj="$1" field="$2" json_body="$3"
  local resp
  resp=$(curl -s -X POST "${BASE_URL}/services/data/v63.0/tooling/sobjects/CustomField" \
    -H "$AUTH" -H "$CT" -H "$ORIGIN" -d "$json_body")
  if echo "$resp" | python3 -c "import sys,json; d=json.load(sys.stdin); exit(0 if d.get('success') else 1)" 2>/dev/null; then
    echo "   ✅ Field: $obj.$field"
  else
    echo "   ⚠  Field $obj.$field: $resp"
  fi
}

post_record() {
  local obj="$1"
  local data="$2"
  local label="$3"

  local resp
  resp=$(curl -s -X POST "$API/sobjects/$obj" -H "$AUTH" -H "$CT" -H "$ORIGIN" -d "$data" 2>&1)

  local record_id
  record_id=$(echo "$resp" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['id']) if d.get('success') or 'id' in d else exit(1)" 2>/dev/null) || {
    echo "   ⚠  Failed: $label  →  $resp"
    ((failed++)) || true
    return 0
  }
  echo "   ✅ $label → $record_id"
  ((created++)) || true
  LAST_ID="$record_id"
}

# ═════════════════════════════════════════════════════════
# Phase 1: Ensure CRM Objects & Fields exist
# ═════════════════════════════════════════════════════════
echo ""
echo "🏗️  Phase 1: Ensuring CRM objects exist..."

ensure_object "Account" "Account" "Accounts"
ensure_object "Contact" "Contact" "Contacts"
ensure_object "Campaign" "Campaign" "Campaigns"
ensure_object "Opportunity" "Opportunity" "Opportunities"
ensure_object "CampaignMember" "Campaign Member" "Campaign Members"
ensure_object "Lead" "Lead" "Leads"

echo ""
echo "🔧 Phase 1b: Ensuring key fields..."

# Campaign fields
ensure_field "Campaign" "Description" "Description" "LongTextArea" ",\"length\":32000"
ensure_field "Campaign" "Status" "Status" "Text"
ensure_field "Campaign" "Type" "Type" "Text"
ensure_field "Campaign" "IsActive" "Active" "Checkbox"
ensure_field "Campaign" "StartDate" "Start Date" "Date"
ensure_field "Campaign" "EndDate" "End Date" "Date"
ensure_field "Campaign" "ParentId" "Parent Campaign" "Text"

# Campaign — picklist fields for C1/C2 picklist dropdown verification
ensure_field_json "Campaign" "CampaignStatus__c" '{"FullName":"Campaign.CampaignStatus__c","TableEnumOrId":"Campaign","Metadata":{"label":"Campaign Status","type":"Picklist","picklist":{"picklistValues":[{"fullName":"Planned","label":"Planned","default":true},{"fullName":"In Progress","label":"In Progress","default":false},{"fullName":"Completed","label":"Completed","default":false},{"fullName":"Aborted","label":"Aborted","default":false}],"sorted":false}}}'
ensure_field_json "Campaign" "TestPicklist__c" '{"FullName":"Campaign.TestPicklist__c","TableEnumOrId":"Campaign","Metadata":{"label":"Test Picklist","type":"Picklist","picklist":{"picklistValues":[{"fullName":"Option A","label":"Option A","default":false},{"fullName":"Option B","label":"Option B","default":false},{"fullName":"Option C","label":"Option C","default":true}],"sorted":false}}}'

# Opportunity fields
ensure_field "Opportunity" "Description" "Description" "LongTextArea" ",\"length\":32000"
ensure_field "Opportunity" "StageName" "Stage" "Text"
ensure_field "Opportunity" "Amount" "Amount" "Currency" ",\"precision\":18,\"scale\":2"
ensure_field "Opportunity" "Close_Date" "Close Date" "Date"
ensure_field "Opportunity" "Probability" "Probability (%)" "Percent" ",\"precision\":5,\"scale\":2"

# Opportunity — multipicklist field for F2 verification
ensure_field_json "Opportunity" "Tags__c" '{"FullName":"Opportunity.Tags__c","TableEnumOrId":"Opportunity","Metadata":{"label":"Tags","type":"MultiselectPicklist","picklist":{"picklistValues":[{"fullName":"Enterprise","label":"Enterprise","default":false},{"fullName":"SMB","label":"SMB","default":false},{"fullName":"Government","label":"Government","default":false},{"fullName":"Healthcare","label":"Healthcare","default":false},{"fullName":"Education","label":"Education","default":false}],"sorted":false}}}'

# CampaignMember fields
ensure_field "CampaignMember" "CampaignId" "Campaign" "Text"
ensure_field "CampaignMember" "Status" "Status" "Text"
ensure_field "CampaignMember" "CompanyOrAccount" "Company / Account" "Text"
ensure_field "CampaignMember" "Type" "Type" "Text"
ensure_field "CampaignMember" "ContactId" "Contact" "Text"
ensure_field "CampaignMember" "LeadId" "Lead" "Text"

# Lead fields — for K2 (lead convert modal) verification
ensure_field "Lead" "Company" "Company" "Text"
ensure_field "Lead" "Email" "Email" "Email"
ensure_field "Lead" "Phone" "Phone" "Phone"
ensure_field "Lead" "Description" "Description" "LongTextArea" ",\"length\":32000"
ensure_field_json "Lead" "LeadSource" '{"FullName":"Lead.LeadSource","TableEnumOrId":"Lead","Metadata":{"label":"Lead Source","type":"Picklist","picklist":{"picklistValues":[{"fullName":"Web","label":"Web","default":true},{"fullName":"Phone","label":"Phone Inquiry","default":false},{"fullName":"Partner","label":"Partner Referral","default":false},{"fullName":"Event","label":"Event","default":false},{"fullName":"Other","label":"Other","default":false}],"sorted":false}}}'
ensure_field_json "Lead" "Status" '{"FullName":"Lead.Status","TableEnumOrId":"Lead","Metadata":{"label":"Status","type":"Picklist","picklist":{"picklistValues":[{"fullName":"Open","label":"Open - Not Contacted","default":true},{"fullName":"Working","label":"Working - Contacted","default":false},{"fullName":"Closed_Converted","label":"Closed - Converted","default":false},{"fullName":"Closed_Lost","label":"Closed - Not Converted","default":false}],"sorted":false}}}'

# Account fields
ensure_field "Account" "Industry" "Industry" "Text"
ensure_field "Account" "Phone" "Phone" "Phone"
ensure_field "Account" "Website" "Website" "Url"
ensure_field "Account" "BillingCity" "Billing City" "Text"

# Contact fields (with Lookup to Account for dot-notation testing)
ensure_field "Contact" "Email" "Email" "Email"
ensure_field "Contact" "Phone" "Phone" "Phone"
ensure_field "Contact" "Title" "Title" "Text"
ensure_field_json "Contact" "AccountId" '{"FullName":"Contact.AccountId","TableEnumOrId":"Contact","Metadata":{"label":"Account","type":"Lookup","referenceTo":"Account","relationshipName":"Account"}}'

# Opportunity — Lookup to Account for dot-notation testing
ensure_field_json "Opportunity" "AccountId" '{"FullName":"Opportunity.AccountId","TableEnumOrId":"Opportunity","Metadata":{"label":"Account","type":"Lookup","referenceTo":"Account","relationshipName":"Account"}}'

# NOTE: New fields created above are only visible to the record API after a
# backend restart (schema cache reload). If this is a fresh DB run, the script
# will warn on fields like LeadSource, Tags__c etc. Run the script again after
# restarting the backend to populate records using those fields.
echo ""
echo "🔄 Waiting for schema cache refresh..."
sleep 2

# ═════════════════════════════════════════════════════════
# Phase 2: Populate Records
# ═════════════════════════════════════════════════════════
echo ""
echo "🏢 Phase 2a: Creating Accounts..."

post_record "Account" '{
  "Name": "Acme Corp",
  "Industry": "Technology",
  "Website": "https://acme.example.com",
  "BillingCity": "San Francisco"
}' "Account: Acme Corp"
ACME_ID="${LAST_ID:-}"

post_record "Account" '{
  "Name": "Globex International",
  "Industry": "Manufacturing",
  "Website": "https://globex.example.com",
  "BillingCity": "Chicago"
}' "Account: Globex International"
GLOBEX_ID="${LAST_ID:-}"

post_record "Account" '{
  "Name": "Stark Industries",
  "Industry": "Defense",
  "Website": "https://stark.example.com",
  "BillingCity": "New York"
}' "Account: Stark Industries"
STARK_ID="${LAST_ID:-}"

post_record "Account" '{
  "Name": "Wayne Enterprises",
  "Industry": "Conglomerate",
  "Website": "https://wayne.example.com",
  "BillingCity": "Gotham"
}' "Account: Wayne Enterprises"
WAYNE_ID="${LAST_ID:-}"

post_record "Account" '{
  "Name": "Umbrella Corp",
  "Industry": "Pharmaceuticals",
  "Website": "https://umbrella.example.com",
  "BillingCity": "Raccoon City"
}' "Account: Umbrella Corp"
UMBRELLA_ID="${LAST_ID:-}"

echo ""
echo "👤 Phase 2b: Creating Contacts (with Account lookups)..."

if [ -n "$ACME_ID" ]; then
  post_record "Contact" "{
    \"Name\": \"Alice Johnson\",
    \"Email\": \"alice@acme.com\",
    \"Title\": \"VP of Sales\",
    \"AccountId\": \"$ACME_ID\"
  }" "Contact: Alice Johnson (Acme)"

  post_record "Contact" "{
    \"Name\": \"Bob Smith\",
    \"Email\": \"bob@acme.com\",
    \"Title\": \"Director of Engineering\",
    \"AccountId\": \"$ACME_ID\"
  }" "Contact: Bob Smith (Acme)"
fi

if [ -n "$GLOBEX_ID" ]; then
  post_record "Contact" "{
    \"Name\": \"Charlie Brown\",
    \"Email\": \"charlie@globex.com\",
    \"Title\": \"CTO\",
    \"AccountId\": \"$GLOBEX_ID\"
  }" "Contact: Charlie Brown (Globex)"
fi

if [ -n "$STARK_ID" ]; then
  post_record "Contact" "{
    \"Name\": \"Pepper Potts\",
    \"Email\": \"pepper@stark.com\",
    \"Title\": \"CEO\",
    \"AccountId\": \"$STARK_ID\"
  }" "Contact: Pepper Potts (Stark)"
fi

if [ -n "$WAYNE_ID" ]; then
  post_record "Contact" "{
    \"Name\": \"Alfred Pennyworth\",
    \"Email\": \"alfred@wayne.com\",
    \"Title\": \"Executive Assistant\",
    \"AccountId\": \"$WAYNE_ID\"
  }" "Contact: Alfred Pennyworth (Wayne)"
fi

echo ""
echo "📣 Phase 2c: Creating Campaigns..."

post_record "Campaign" '{
  "Name": "Q1 2026 Product Launch",
  "Status": "Planned",
  "Type": "Product Launch",
  "IsActive": true,
  "StartDate": "2026-01-15",
  "EndDate": "2026-03-31",
  "Description": "Major product launch campaign for NexusCRM v3.0"
}' "Campaign: Q1 2026 Product Launch"

post_record "Campaign" '{
  "Name": "Spring Webinar Series",
  "Status": "In Progress",
  "Type": "Webinar",
  "IsActive": true,
  "StartDate": "2026-02-01",
  "EndDate": "2026-05-30",
  "Description": "Monthly webinar series covering CRM best practices"
}' "Campaign: Spring Webinar Series"

post_record "Campaign" '{
  "Name": "Partner Referral Program",
  "Status": "Planned",
  "Type": "Referral Program",
  "IsActive": true,
  "StartDate": "2026-03-01",
  "EndDate": "2026-12-31",
  "Description": "Channel partner referral incentive program"
}' "Campaign: Partner Referral Program"

post_record "Campaign" '{
  "Name": "Annual Conference 2026",
  "Status": "Planned",
  "Type": "Conference",
  "IsActive": false,
  "StartDate": "2026-09-15",
  "EndDate": "2026-09-17",
  "Description": "NexusCRM annual user conference"
}' "Campaign: Annual Conference 2026"

post_record "Campaign" '{
  "Name": "Email Drip - Trial Users",
  "Status": "Completed",
  "Type": "Email",
  "IsActive": false,
  "StartDate": "2025-10-01",
  "EndDate": "2025-12-31",
  "Description": "Automated email nurture sequence for trial sign-ups"
}' "Campaign: Email Drip - Trial Users"

# ── Campaign Member Statuses ──
echo ""
echo "📋 Creating CampaignMemberStatuses..."

CAMP_ID=$(curl -s "$API/query?q=SELECT+Id+FROM+Campaign+LIMIT+1" -H "$AUTH" -H "$ORIGIN" | python3 -c "import sys,json; print(json.load(sys.stdin)['records'][0]['Id'])" 2>/dev/null || echo "")

if [ -n "$CAMP_ID" ]; then
  post_record "CampaignMemberStatus" "{
    \"CampaignId\": \"$CAMP_ID\",
    \"Label\": \"Invited\",
    \"HasResponded\": false,
    \"IsDefault\": false,
    \"SortOrder\": 3
  }" "CampaignMemberStatus: Invited"

  post_record "CampaignMemberStatus" "{
    \"CampaignId\": \"$CAMP_ID\",
    \"Label\": \"Attended\",
    \"HasResponded\": true,
    \"IsDefault\": false,
    \"SortOrder\": 4
  }" "CampaignMemberStatus: Attended"

  post_record "CampaignMemberStatus" "{
    \"CampaignId\": \"$CAMP_ID\",
    \"Label\": \"No Show\",
    \"HasResponded\": false,
    \"IsDefault\": false,
    \"SortOrder\": 5
  }" "CampaignMemberStatus: No Show"
else
  echo "   ⚠  No campaigns found, skipping CampaignMemberStatus"
fi

# ── Opportunities ──
echo ""
echo "💰 Creating Opportunities..."

ACME_REF=""
[ -n "$ACME_ID" ] && ACME_REF=",\"AccountId\": \"$ACME_ID\""

GLOBEX_REF=""
[ -n "$GLOBEX_ID" ] && GLOBEX_REF=",\"AccountId\": \"$GLOBEX_ID\""

STARK_REF=""
[ -n "$STARK_ID" ] && STARK_REF=",\"AccountId\": \"$STARK_ID\""

WAYNE_REF=""
[ -n "$WAYNE_ID" ] && WAYNE_REF=",\"AccountId\": \"$WAYNE_ID\""

UMBRELLA_REF=""
[ -n "$UMBRELLA_ID" ] && UMBRELLA_REF=",\"AccountId\": \"$UMBRELLA_ID\""

post_record "Opportunity" "{
  \"Name\": \"Acme Corp - Enterprise License\",
  \"StageName\": \"Negotiation\",
  \"Amount\": \"125000\",
  \"Close_Date\": \"2026-04-15\",
  \"Probability\": \"75\",
  \"OwnerId\": \"$SALES_ID\",
  \"Description\": \"Enterprise license deal with Acme Corp for 500 seats\"
  $ACME_REF
}" "Opportunity: Acme Corp - Enterprise License"

post_record "Opportunity" "{
  \"Name\": \"Globex Inc - Platform Migration\",
  \"StageName\": \"Qualification\",
  \"Amount\": \"85000\",
  \"Close_Date\": \"2026-06-30\",
  \"Probability\": \"40\",
  \"OwnerId\": \"$SALES_ID\",
  \"Description\": \"Migration from legacy CRM to NexusCRM platform\"
  $GLOBEX_REF
}" "Opportunity: Globex Inc - Platform Migration"

post_record "Opportunity" "{
  \"Name\": \"Initech - Annual Renewal\",
  \"StageName\": \"Closed Won\",
  \"Amount\": \"45000\",
  \"Close_Date\": \"2026-01-31\",
  \"Probability\": \"100\",
  \"OwnerId\": \"$DEAL_ID\",
  \"Description\": \"Annual SaaS subscription renewal\"
}" "Opportunity: Initech - Annual Renewal"

post_record "Opportunity" "{
  \"Name\": \"Umbrella Corp - POC\",
  \"StageName\": \"Prospecting\",
  \"Amount\": \"200000\",
  \"Close_Date\": \"2026-08-30\",
  \"Probability\": \"20\",
  \"OwnerId\": \"$DEAL_ID\",
  \"Description\": \"Proof of concept for pharmaceutical research division\"
  $UMBRELLA_REF
}" "Opportunity: Umbrella Corp - POC"

post_record "Opportunity" "{
  \"Name\": \"Wayne Enterprises - Add-On\",
  \"StageName\": \"Proposal\",
  \"Amount\": \"62000\",
  \"Close_Date\": \"2026-05-15\",
  \"Probability\": \"60\",
  \"OwnerId\": \"$SALES_ID\",
  \"Description\": \"Additional modules: analytics dashboard and workflow automation\"
  $WAYNE_REF
}" "Opportunity: Wayne Enterprises - Add-On"

post_record "Opportunity" "{
  \"Name\": \"Stark Industries - Custom Dev\",
  \"StageName\": \"Negotiation\",
  \"Amount\": \"350000\",
  \"Close_Date\": \"2026-07-01\",
  \"Probability\": \"65\",
  \"OwnerId\": \"$DEAL_ID\",
  \"Description\": \"Custom integration with Stark Industries ERP platform\"
  $STARK_REF
}" "Opportunity: Stark Industries - Custom Dev"

post_record "Opportunity" "{
  \"Name\": \"Oscorp - Closed Lost\",
  \"StageName\": \"Closed Lost\",
  \"Amount\": \"78000\",
  \"Close_Date\": \"2026-02-28\",
  \"Probability\": \"0\",
  \"OwnerId\": \"$SALES_ID\",
  \"Description\": \"Lost to competitor - pricing concerns\"
}" "Opportunity: Oscorp - Closed Lost"

post_record "Opportunity" "{
  \"Name\": \"Cyberdyne Systems - Initial\",
  \"StageName\": \"Needs Analysis\",
  \"Amount\": \"155000\",
  \"Close_Date\": \"2026-09-15\",
  \"Probability\": \"30\",
  \"OwnerId\": \"$DEAL_ID\",
  \"Description\": \"New customer evaluation for AI-enhanced CRM features\"
}" "Opportunity: Cyberdyne Systems - Initial"

# ── Campaign Members ──
echo ""
echo "👥 Creating Campaign Members..."

ALL_CAMPS=$(curl -s "$API/query?q=SELECT+Id+FROM+Campaign+LIMIT+5" -H "$AUTH" -H "$ORIGIN" | python3 -c "
import sys, json
d = json.load(sys.stdin)
for r in d.get('records', []):
    print(r['Id'])
" 2>/dev/null || true)

if [ -n "$ALL_CAMPS" ]; then
  CAMP_ARR=($ALL_CAMPS)
  NAMES=("Alice Johnson" "Bob Smith" "Charlie Brown" "Diana Prince" "Eve Torres" "Frank Castle" "Grace Hopper" "Hank Pym")
  STATUSES=("Sent" "Responded" "Sent" "Responded" "Sent" "Sent" "Responded" "Sent")
  COMPANIES=("Acme Corp" "Globex Inc" "Initech" "Umbrella Corp" "Wayne Enterprises" "Stark Industries" "Oscorp" "Cyberdyne")

  for i in "${!NAMES[@]}"; do
    camp_idx=$((i % ${#CAMP_ARR[@]}))
    post_record "CampaignMember" "{
      \"CampaignId\": \"${CAMP_ARR[$camp_idx]}\",
      \"Name\": \"${NAMES[$i]}\",
      \"Status\": \"${STATUSES[$i]}\",
      \"CompanyOrAccount\": \"${COMPANIES[$i]}\",
      \"Type\": \"Contact\"
    }" "CampaignMember: ${NAMES[$i]}"
  done
else
  echo "   ⚠  No campaigns found, skipping CampaignMember creation"
fi

# ── Leads (for K2 Lead Convert verification) ──
echo ""
echo "🎯 Creating Leads..."

post_record "Lead" '{
  "Name": "Sarah Connor",
  "Company": "Skynet Defense",
  "Email": "sarah@skynet.com",
  "LeadSource": "Web",
  "Status": "Open"
}' "Lead: Sarah Connor"

post_record "Lead" '{
  "Name": "John Doe",
  "Company": "Acme Corp",
  "Email": "jdoe@acme.com",
  "LeadSource": "Partner",
  "Status": "Working"
}' "Lead: John Doe"

post_record "Lead" '{
  "Name": "Jane Smith",
  "Company": "Globex International",
  "Email": "jsmith@globex.com",
  "LeadSource": "Event",
  "Status": "Open"
}' "Lead: Jane Smith"

post_record "Lead" '{
  "Name": "Tony Stark",
  "Company": "Stark Industries",
  "Email": "tony@stark.com",
  "LeadSource": "Web",
  "Status": "Working"
}' "Lead: Tony Stark"

post_record "Lead" '{
  "Name": "Bruce Wayne",
  "Company": "Wayne Enterprises",
  "Email": "bruce@wayne.com",
  "LeadSource": "Phone",
  "Status": "Open"
}' "Lead: Bruce Wayne"

# ── Extra Opportunities (to trigger pagination — need >20 total) ──
echo ""
echo "📊 Creating extra Opportunities for pagination test..."

for i in $(seq 1 25); do
  stages=("Prospecting" "Qualification" "Proposal" "Negotiation" "Closed Won" "Closed Lost")
  stage=${stages[$((i % 6))]}
  amt=$(( (i * 15000) + 10000 ))
  prob=$(( (i * 12) % 100 ))
  owner=$SALES_ID
  [ $((i % 2)) -eq 0 ] && owner=$DEAL_ID
  tags="Enterprise;SMB"
  [ $((i % 3)) -eq 0 ] && tags="Government;Healthcare"
  [ $((i % 5)) -eq 0 ] && tags="Education;Enterprise;Government"
  post_record "Opportunity" "{
    \"Name\": \"Auto-Opp-$i ($stage)\",
    \"StageName\": \"$stage\",
    \"Amount\": \"$amt\",
    \"Close_Date\": \"2026-$(printf '%02d' $(( (i % 12) + 1 )))-15\",
    \"Probability\": \"$prob\",
    \"OwnerId\": \"$owner\",
    \"Tags__c\": \"$tags\",
    \"Description\": \"Auto-generated opportunity #$i for pagination testing\"
  }" "Opportunity: Auto-Opp-$i"
done

# ── Update Campaigns with picklist values ──
echo ""
echo "🎨 Setting picklist values on Campaigns..."

ALL_CAMP_IDS=$(curl -s "$API/query?q=SELECT+Id+FROM+Campaign" -H "$AUTH" -H "$ORIGIN" | python3 -c "
import sys, json
d = json.load(sys.stdin)
for r in d.get('records', []):
    print(r['Id'])
" 2>/dev/null || true)

if [ -n "$ALL_CAMP_IDS" ]; then
  CAMP_ID_ARR=($ALL_CAMP_IDS)
  PSTATUSES=("Planned" "In Progress" "Completed" "Aborted" "Planned")
  PPICKLIST=("Option A" "Option B" "Option C" "Option A" "Option B")
  for idx in "${!CAMP_ID_ARR[@]}"; do
    cid="${CAMP_ID_ARR[$idx]}"
    ps="${PSTATUSES[$((idx % 5))]}"
    pp="${PPICKLIST[$((idx % 5))]}"
    curl -s -X PATCH "$API/sobjects/Campaign/$cid" -H "$AUTH" -H "$CT" -H "$ORIGIN" \
      -d "{\"CampaignStatus__c\":\"$ps\",\"TestPicklist__c\":\"$pp\"}" >/dev/null 2>&1
    echo "   ✅ Campaign $cid: CampaignStatus=$ps, TestPicklist=$pp"
  done
fi

# ── Apply Campaign Layout ──
echo ""
echo "📐 Applying Campaign layout..."
bash scripts/apply_campaign_layout.sh 2>&1 || echo "   ⚠  Layout script returned non-zero (may already exist)"

# ═════════════════════════════════════════════════════════
# Summary
# ═════════════════════════════════════════════════════════
echo ""
echo "═══════════════════════════════════════════════════════"
echo "📊 Data Population Complete"
echo "   Created: $created records"
echo "   Failed:  $failed records"
echo "═══════════════════════════════════════════════════════"

echo ""
echo "📈 Final record counts:"
for obj in Account Contact Campaign CampaignMember CampaignMemberStatus Opportunity Lead; do
  count=$(curl -s "$API/query?q=SELECT+Id+FROM+${obj}" -H "$AUTH" -H "$ORIGIN" | python3 -c "import sys,json; print(json.load(sys.stdin).get('totalSize',0))" 2>/dev/null || echo "?")
  printf "   %-30s %s\n" "$obj" "$count"
done
