/**
 * Seed lab tests and link them to health packages via packageTest junction.
 * Run: cd helix-engage && npx tsx scripts/seed-lab-tests.ts
 *
 * Prerequisites: health packages already seeded via seed-new-entities.ts
 *
 * Platform field mapping:
 *   LabTest: testCategory→category, testDepartment→department,
 *     durationMinutes→durationMin, isActive→active, preparation→preparationInstructions
 *   PackageTest: position→order, isMandatory→mandatory
 */

const GQL = process.env.SEED_GQL ?? 'http://localhost:4000/graphql';
const SUB = 'fortytwo-dev';
const ORIGIN = process.env.SEED_ORIGIN ?? 'http://fortytwo-dev.localhost:4010';

let token = '';

async function gql(query: string, variables?: any) {
    const h: Record<string, string> = { 'Content-Type': 'application/json', 'X-Workspace-Subdomain': SUB };
    if (token) h['Authorization'] = `Bearer ${token}`;
    const r = await fetch(GQL, { method: 'POST', headers: h, body: JSON.stringify({ query, variables }) });
    const d: any = await r.json();
    if (d.errors) { console.error('❌', d.errors[0].message); throw new Error(d.errors[0].message); }
    return d.data;
}

async function auth() {
    const d1 = await gql(`mutation { getLoginTokenFromCredentials(email: "dev@fortytwo.dev", password: "tim@apple.dev", origin: "${ORIGIN}") { loginToken { token } } }`);
    const lt = d1.getLoginTokenFromCredentials.loginToken.token;
    const d2 = await gql(`mutation { getAuthTokensFromLoginToken(loginToken: "${lt}", origin: "${ORIGIN}") { tokens { accessOrWorkspaceAgnosticToken { token } } } }`);
    token = d2.getAuthTokensFromLoginToken.tokens.accessOrWorkspaceAgnosticToken.token;
}

async function mk(entity: string, data: any): Promise<string> {
    const cap = entity[0].toUpperCase() + entity.slice(1);
    const d = await gql(`mutation($data: ${cap}CreateInput!) { create${cap}(data: $data) { id } }`, { data });
    return d[`create${cap}`].id;
}

async function main() {
    console.log('🧪 Seeding lab tests and package linkages...\n');
    await auth();
    console.log('✅ Auth OK\n');

    // Fetch existing health package IDs
    const pkgData = await gql(`{ healthPackages(first: 10) { edges { node { id packageName } } } }`);
    const pkgs: Record<string, string> = {};
    for (const e of pkgData.healthPackages.edges) {
        pkgs[e.node.packageName] = e.node.id;
    }
    console.log(`📦 Found ${Object.keys(pkgs).length} packages: ${Object.keys(pkgs).join(', ')}\n`);

    // ═══════════════════════════════════════════
    // LAB TESTS
    // ═══════════════════════════════════════════
    console.log('🧪 Lab Tests');

    // Blood tests
    const cbc = await mk('labTest', { name: 'CBC', testName: 'Complete Blood Count', testCode: 'CBC-001', category: 'BLOOD_TEST', department: 'PATHOLOGY', price: { amountMicros: 350_000_000, currencyCode: 'INR' }, durationMin: 15, sampleType: 'Blood (EDTA tube)', preparationInstructions: 'No fasting required', active: true });
    console.log('   CBC');

    const lipid = await mk('labTest', { name: 'Lipid Profile', testName: 'Lipid Profile', testCode: 'LIP-001', category: 'BLOOD_TEST', department: 'PATHOLOGY', price: { amountMicros: 500_000_000, currencyCode: 'INR' }, durationMin: 15, sampleType: 'Blood (serum)', preparationInstructions: '12-hour fasting required', active: true });
    console.log('   Lipid Profile');

    const lft = await mk('labTest', { name: 'Liver Function Test', testName: 'Liver Function Test', testCode: 'LFT-001', category: 'BLOOD_TEST', department: 'PATHOLOGY', price: { amountMicros: 450_000_000, currencyCode: 'INR' }, durationMin: 15, sampleType: 'Blood (serum)', preparationInstructions: '12-hour fasting recommended', active: true });
    console.log('   LFT');

    const kft = await mk('labTest', { name: 'Kidney Function Test', testName: 'Kidney Function Test', testCode: 'KFT-001', category: 'BLOOD_TEST', department: 'PATHOLOGY', price: { amountMicros: 450_000_000, currencyCode: 'INR' }, durationMin: 15, sampleType: 'Blood (serum)', preparationInstructions: 'No fasting required', active: true });
    console.log('   KFT');

    const thyroid = await mk('labTest', { name: 'Thyroid Panel', testName: 'Thyroid Profile (T3, T4, TSH)', testCode: 'THY-001', category: 'HORMONE', department: 'PATHOLOGY', price: { amountMicros: 600_000_000, currencyCode: 'INR' }, durationMin: 15, sampleType: 'Blood (serum)', preparationInstructions: 'No fasting required. Collect sample before thyroid medication.', active: true });
    console.log('   Thyroid Panel');

    const bloodSugar = await mk('labTest', { name: 'Blood Sugar (Fasting + PP)', testName: 'Blood Sugar Fasting & Post-Prandial', testCode: 'GLU-001', category: 'BLOOD_TEST', department: 'PATHOLOGY', price: { amountMicros: 200_000_000, currencyCode: 'INR' }, durationMin: 10, sampleType: 'Blood (fluoride tube)', preparationInstructions: '10-12 hour fasting for FBS; 2h after meal for PP', active: true });
    console.log('   Blood Sugar');

    const hba1c = await mk('labTest', { name: 'HbA1c', testName: 'Glycated Hemoglobin', testCode: 'HBA-001', category: 'BLOOD_TEST', department: 'PATHOLOGY', price: { amountMicros: 400_000_000, currencyCode: 'INR' }, durationMin: 15, sampleType: 'Blood (EDTA tube)', preparationInstructions: 'No fasting required', active: true });
    console.log('   HbA1c');

    const vitD = await mk('labTest', { name: 'Vitamin D', testName: 'Vitamin D (25-Hydroxy)', testCode: 'VIT-D01', category: 'BLOOD_TEST', department: 'PATHOLOGY', price: { amountMicros: 800_000_000, currencyCode: 'INR' }, durationMin: 15, sampleType: 'Blood (serum)', preparationInstructions: 'No fasting required', active: true });
    console.log('   Vitamin D');

    const calcium = await mk('labTest', { name: 'Calcium', testName: 'Serum Calcium', testCode: 'CAL-001', category: 'BLOOD_TEST', department: 'PATHOLOGY', price: { amountMicros: 200_000_000, currencyCode: 'INR' }, durationMin: 10, sampleType: 'Blood (serum)', preparationInstructions: 'No fasting required', active: true });
    console.log('   Calcium');

    const uricAcid = await mk('labTest', { name: 'Uric Acid', testName: 'Serum Uric Acid', testCode: 'URA-001', category: 'BLOOD_TEST', department: 'PATHOLOGY', price: { amountMicros: 200_000_000, currencyCode: 'INR' }, durationMin: 10, sampleType: 'Blood (serum)', preparationInstructions: 'No fasting required', active: true });
    console.log('   Uric Acid');

    const raFactor = await mk('labTest', { name: 'RA Factor', testName: 'Rheumatoid Factor', testCode: 'RAF-001', category: 'BLOOD_TEST', department: 'PATHOLOGY', price: { amountMicros: 500_000_000, currencyCode: 'INR' }, durationMin: 15, sampleType: 'Blood (serum)', preparationInstructions: 'No fasting required', active: true });
    console.log('   RA Factor');

    const hsCrp = await mk('labTest', { name: 'hs-CRP', testName: 'High-Sensitivity C-Reactive Protein', testCode: 'CRP-001', category: 'BLOOD_TEST', department: 'PATHOLOGY', price: { amountMicros: 600_000_000, currencyCode: 'INR' }, durationMin: 15, sampleType: 'Blood (serum)', preparationInstructions: 'No fasting required', active: true });
    console.log('   hs-CRP');

    const homocysteine = await mk('labTest', { name: 'Homocysteine', testName: 'Serum Homocysteine', testCode: 'HCY-001', category: 'BLOOD_TEST', department: 'PATHOLOGY', price: { amountMicros: 700_000_000, currencyCode: 'INR' }, durationMin: 15, sampleType: 'Blood (serum)', preparationInstructions: '12-hour fasting recommended', active: true });
    console.log('   Homocysteine');

    await auth();

    // Hormone panel
    const amh = await mk('labTest', { name: 'AMH', testName: 'Anti-Müllerian Hormone', testCode: 'AMH-001', category: 'HORMONE', department: 'GYNECOLOGY', price: { amountMicros: 1_500_000_000, currencyCode: 'INR' }, durationMin: 15, sampleType: 'Blood (serum)', preparationInstructions: 'No fasting. Can be done on any day of cycle.', active: true });
    console.log('   AMH');

    const fsh = await mk('labTest', { name: 'FSH', testName: 'Follicle-Stimulating Hormone', testCode: 'FSH-001', category: 'HORMONE', department: 'GYNECOLOGY', price: { amountMicros: 500_000_000, currencyCode: 'INR' }, durationMin: 15, sampleType: 'Blood (serum)', preparationInstructions: 'Day 2-3 of menstrual cycle preferred', active: true });
    console.log('   FSH');

    const lh = await mk('labTest', { name: 'LH', testName: 'Luteinizing Hormone', testCode: 'LH-001', category: 'HORMONE', department: 'GYNECOLOGY', price: { amountMicros: 500_000_000, currencyCode: 'INR' }, durationMin: 15, sampleType: 'Blood (serum)', preparationInstructions: 'Day 2-3 of menstrual cycle preferred', active: true });
    console.log('   LH');

    const estradiol = await mk('labTest', { name: 'Estradiol', testName: 'Estradiol (E2)', testCode: 'EST-001', category: 'HORMONE', department: 'GYNECOLOGY', price: { amountMicros: 600_000_000, currencyCode: 'INR' }, durationMin: 15, sampleType: 'Blood (serum)', preparationInstructions: 'Day 2-3 of menstrual cycle preferred', active: true });
    console.log('   Estradiol');

    const prolactin = await mk('labTest', { name: 'Prolactin', testName: 'Serum Prolactin', testCode: 'PRL-001', category: 'HORMONE', department: 'GYNECOLOGY', price: { amountMicros: 500_000_000, currencyCode: 'INR' }, durationMin: 15, sampleType: 'Blood (serum)', preparationInstructions: 'Fasting. Morning sample preferred.', active: true });
    console.log('   Prolactin');

    // Imaging
    const ecg = await mk('labTest', { name: 'ECG', testName: 'Electrocardiogram (12-lead)', testCode: 'ECG-001', category: 'CARDIAC', department: 'CARDIOLOGY', price: { amountMicros: 300_000_000, currencyCode: 'INR' }, durationMin: 15, preparationInstructions: 'No preparation needed', active: true });
    console.log('   ECG');

    const echo = await mk('labTest', { name: '2D Echocardiogram', testName: '2D Echocardiogram with Color Doppler', testCode: 'ECHO-001', category: 'CARDIAC', department: 'CARDIOLOGY', price: { amountMicros: 2_000_000_000, currencyCode: 'INR' }, durationMin: 30, preparationInstructions: 'No preparation needed', active: true });
    console.log('   2D Echo');

    const tmt = await mk('labTest', { name: 'TMT', testName: 'Treadmill Test (Stress Test)', testCode: 'TMT-001', category: 'CARDIAC', department: 'CARDIOLOGY', price: { amountMicros: 1_500_000_000, currencyCode: 'INR' }, durationMin: 45, preparationInstructions: 'Wear comfortable shoes. Light meal 2h before. Avoid caffeine.', active: true });
    console.log('   TMT');

    const chestXray = await mk('labTest', { name: 'Chest X-ray', testName: 'Chest X-ray PA View', testCode: 'XR-001', category: 'IMAGING', department: 'RADIOLOGY', price: { amountMicros: 400_000_000, currencyCode: 'INR' }, durationMin: 10, preparationInstructions: 'Remove metal jewellery', active: true });
    console.log('   Chest X-ray');

    const tvUltrasound = await mk('labTest', { name: 'Transvaginal Ultrasound', testName: 'Transvaginal Ultrasound', testCode: 'TVS-001', category: 'IMAGING', department: 'GYNECOLOGY', price: { amountMicros: 1_200_000_000, currencyCode: 'INR' }, durationMin: 20, preparationInstructions: 'Empty bladder preferred', active: true });
    console.log('   Transvaginal Ultrasound');

    const pelvicUS = await mk('labTest', { name: 'Pelvic Ultrasound', testName: 'Pelvic Ultrasound', testCode: 'PUS-001', category: 'IMAGING', department: 'GYNECOLOGY', price: { amountMicros: 1_000_000_000, currencyCode: 'INR' }, durationMin: 20, preparationInstructions: 'Full bladder required — drink 4-5 glasses of water 1h before', active: true });
    console.log('   Pelvic Ultrasound');

    const mammogram = await mk('labTest', { name: 'Mammogram', testName: 'Digital Mammogram (Bilateral)', testCode: 'MAM-001', category: 'SCREENING', department: 'RADIOLOGY', price: { amountMicros: 1_500_000_000, currencyCode: 'INR' }, durationMin: 20, preparationInstructions: 'Schedule 1 week after period. No deodorant/powder on exam day.', active: true });
    console.log('   Mammogram');

    const boneDensity = await mk('labTest', { name: 'Bone Density Scan', testName: 'DEXA Scan (Bone Mineral Density)', testCode: 'DEXA-001', category: 'BONE_DENSITY', department: 'RADIOLOGY', price: { amountMicros: 1_800_000_000, currencyCode: 'INR' }, durationMin: 15, preparationInstructions: 'No calcium supplements 24h before', active: true });
    console.log('   Bone Density (DEXA)');

    const jointXray = await mk('labTest', { name: 'Joint X-rays', testName: 'Joint X-rays (Knee/Hip/Spine)', testCode: 'XR-JNT01', category: 'IMAGING', department: 'ORTHOPEDICS', price: { amountMicros: 600_000_000, currencyCode: 'INR' }, durationMin: 15, preparationInstructions: 'Remove metal jewellery', active: true });
    console.log('   Joint X-rays');

    await auth();

    // Screening
    const papSmear = await mk('labTest', { name: 'PAP Smear', testName: 'PAP Smear (Cervical Cytology)', testCode: 'PAP-001', category: 'SCREENING', department: 'GYNECOLOGY', price: { amountMicros: 800_000_000, currencyCode: 'INR' }, durationMin: 10, preparationInstructions: 'Avoid intercourse 48h before. Not during menstruation.', active: true });
    console.log('   PAP Smear');

    const bmi = await mk('labTest', { name: 'BMI Assessment', testName: 'BMI & Body Composition', testCode: 'BMI-001', category: 'OTHER', department: 'GENERAL_MEDICINE', price: { amountMicros: 100_000_000, currencyCode: 'INR' }, durationMin: 10, preparationInstructions: 'No preparation needed', active: true });
    console.log('   BMI');

    const vision = await mk('labTest', { name: 'Vision Test', testName: 'Visual Acuity & Eye Screening', testCode: 'VIS-001', category: 'SCREENING', department: 'OPHTHALMOLOGY', price: { amountMicros: 300_000_000, currencyCode: 'INR' }, durationMin: 15, preparationInstructions: 'Bring current glasses if any', active: true });
    console.log('   Vision Test');

    const dental = await mk('labTest', { name: 'Dental Check', testName: 'Dental Screening & Oral Health', testCode: 'DEN-001', category: 'SCREENING', department: 'DENTAL', price: { amountMicros: 300_000_000, currencyCode: 'INR' }, durationMin: 15, preparationInstructions: 'No preparation needed', active: true });
    console.log('   Dental Check');

    const semenAnalysis = await mk('labTest', { name: 'Semen Analysis', testName: 'Semen Analysis (Seminogram)', testCode: 'SEM-001', category: 'OTHER', department: 'PATHOLOGY', price: { amountMicros: 800_000_000, currencyCode: 'INR' }, durationMin: 30, sampleType: 'Semen', preparationInstructions: '3-5 days abstinence required. Collect at lab.', active: true });
    console.log('   Semen Analysis');

    // Consultations
    const cardioConsult = await mk('labTest', { name: 'Cardiologist Consultation', testName: 'Cardiologist Consultation', testCode: 'CON-CAR01', category: 'CONSULTATION', department: 'CARDIOLOGY', price: { amountMicros: 800_000_000, currencyCode: 'INR' }, durationMin: 30, preparationInstructions: 'Bring previous reports and medication list', active: true });
    console.log('   Cardiologist Consultation');

    const gyneConsult = await mk('labTest', { name: 'Gynecologist Consultation', testName: 'Gynecologist Consultation', testCode: 'CON-GYN01', category: 'CONSULTATION', department: 'GYNECOLOGY', price: { amountMicros: 700_000_000, currencyCode: 'INR' }, durationMin: 30, preparationInstructions: 'Bring previous reports and menstrual history', active: true });
    console.log('   Gynecologist Consultation');

    const orthoConsult = await mk('labTest', { name: 'Orthopedic Consultation', testName: 'Orthopedic Consultation', testCode: 'CON-ORT01', category: 'CONSULTATION', department: 'ORTHOPEDICS', price: { amountMicros: 600_000_000, currencyCode: 'INR' }, durationMin: 30, preparationInstructions: 'Bring previous X-rays and reports', active: true });
    console.log('   Orthopedic Consultation');

    const fertilityConsult = await mk('labTest', { name: 'Fertility Specialist Consultation', testName: 'Fertility Specialist Consultation', testCode: 'CON-FER01', category: 'CONSULTATION', department: 'GYNECOLOGY', price: { amountMicros: 1_000_000_000, currencyCode: 'INR' }, durationMin: 45, preparationInstructions: 'Bring previous reports, cycle history, and partner details', active: true });
    console.log('   Fertility Specialist Consultation');

    console.log(`\n   Total: 34 lab tests created\n`);

    await auth();

    // ═══════════════════════════════════════════
    // LINK TESTS TO PACKAGES (packageTest junction)
    // ═══════════════════════════════════════════
    console.log('🔗 Linking tests to packages\n');

    async function link(pkgName: string, tests: { id: string; pos: number; mandatory?: boolean }[]) {
        const pkgId = pkgs[pkgName];
        if (!pkgId) { console.log(`   ⚠️ Package "${pkgName}" not found — skipping`); return; }
        for (const t of tests) {
            await mk('packageTest', {
                name: `${pkgName} — Test #${t.pos}`,
                healthPackageId: pkgId,
                labTestId: t.id,
                order: t.pos,
                mandatory: t.mandatory ?? true,
            });
        }
        console.log(`   ${pkgName}: ${tests.length} tests linked`);
    }

    // Master Health Checkup (11 tests)
    await link('Master Health Checkup', [
        { id: cbc, pos: 1 }, { id: lipid, pos: 2 }, { id: lft, pos: 3 },
        { id: kft, pos: 4 }, { id: thyroid, pos: 5 }, { id: bloodSugar, pos: 6 },
        { id: ecg, pos: 7 }, { id: chestXray, pos: 8 }, { id: bmi, pos: 9 },
        { id: vision, pos: 10 }, { id: dental, pos: 11 },
    ]);

    await auth();

    // Cardiac Screening (8 tests)
    await link('Cardiac Screening', [
        { id: ecg, pos: 1 }, { id: echo, pos: 2 }, { id: tmt, pos: 3 },
        { id: lipid, pos: 4 }, { id: hsCrp, pos: 5 }, { id: homocysteine, pos: 6 },
        { id: hba1c, pos: 7 }, { id: cardioConsult, pos: 8 },
    ]);

    await auth();

    // Women's Wellness (10 tests)
    await link("Women's Wellness Package", [
        { id: papSmear, pos: 1 }, { id: mammogram, pos: 2 }, { id: pelvicUS, pos: 3 },
        { id: thyroid, pos: 4 }, { id: vitD, pos: 5 }, { id: calcium, pos: 6 },
        { id: cbc, pos: 7 }, { id: fsh, pos: 8 }, { id: boneDensity, pos: 9 },
        { id: gyneConsult, pos: 10 },
    ]);

    await auth();

    // Orthopedic Assessment (7 tests)
    await link('Orthopedic Assessment', [
        { id: jointXray, pos: 1 }, { id: boneDensity, pos: 2 }, { id: vitD, pos: 3 },
        { id: calcium, pos: 4 }, { id: uricAcid, pos: 5 }, { id: raFactor, pos: 6 },
        { id: orthoConsult, pos: 7 },
    ]);

    await auth();

    // IVF Consultation (9 tests)
    await link('IVF Consultation Package', [
        { id: amh, pos: 1 }, { id: fsh, pos: 2 }, { id: lh, pos: 3 },
        { id: estradiol, pos: 4 }, { id: prolactin, pos: 5 }, { id: thyroid, pos: 6 },
        { id: tvUltrasound, pos: 7 }, { id: semenAnalysis, pos: 8 },
        { id: fertilityConsult, pos: 9 },
    ]);

    console.log('\n🎉 Done!');
    console.log('   34 lab tests · 45 package-test linkages across 5 packages');
}

main().catch(e => { console.error('💥', e.message); process.exit(1); });
