<?php
declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

/**
 * Starter SDS catalogue for the primary tenant. Real-world materials a plant
 * operator will actually recognise; review dates spread across the calendar
 * so the "review overdue / due soon" dashboard tile has meaningful data
 * without waiting for someone to author sheets by hand.
 *
 * All dates are anchored to the current date at migration time so the tile
 * shows a realistic mix regardless of when the migration is run.
 */
final class SeedSdsLibrary extends AbstractMigration
{
    public function change(): void
    {
        $tenantId = (int) ($this->fetchRow(
            "SELECT tenant_id FROM tenants WHERE subdomain = 'orchid' LIMIT 1"
        )['tenant_id'] ?? 0);
        if ($tenantId === 0) return;

        $today = date('Y-m-d');
        $offset = fn(int $days): string => date('Y-m-d', strtotime("{$days} days"));

        $rows = [
            // code, name, manufacturer, supplier, cas, hazard_class, ppe, hazards,
            // storage_notes, first_aid, disposal_notes, issued_at, review_at
            [
                'SDS-001', 'Diesel Fuel (Ultra-Low Sulphur)', 'TotalEnergies', 'Puma Energy TZ Ltd',
                '68334-30-5', 'flammable',
                'Nitrile gloves, safety goggles, FR overalls, steel-toe boots',
                "Flammable liquid + vapour (Cat 3). Skin/eye irritant on prolonged contact.\nAspiration hazard if swallowed — can cause lung damage.",
                "Cool, well-ventilated bunded area away from ignition sources.\nMax storage 90 days; older stock develops microbial growth.\nKeep containers earthed to prevent static.",
                "Eye: rinse 15 min with water. Skin: wash with soap + water.\nInhalation: fresh air. Ingestion: DO NOT induce vomiting — call medic.",
                'Waste-oil contractor. Never discharge to storm drain or ground.',
                '2025-06-15', $offset(120),
            ],
            [
                'SDS-002', 'Engine Oil 15W-40 (CI-4)', 'Shell', 'Shell Tanzania',
                null, 'health',
                'Nitrile gloves, safety goggles',
                "Prolonged skin contact can cause dermatitis.\nUsed oil contains combustion by-products — treat as carcinogenic.",
                "Sealed drums, off ground on pallets. Bunded area required.\nUsed oil to separate labelled container — never mix with coolant.",
                "Skin: wash promptly with soap + water. Do not use solvents.\nEye: rinse 10 min. Ingestion: no vomiting — call medic.",
                'Licensed waste-oil recycler. Manifest required for each shipment.',
                '2025-03-10', $offset(30),
            ],
            [
                'SDS-003', 'Hydraulic Oil ISO VG 46', 'Mobil', 'Puma Energy TZ Ltd',
                null, 'health',
                'Nitrile gloves, safety goggles',
                'Skin irritant on prolonged contact. High-pressure injection hazard — leaks under pressure can penetrate skin.',
                "Sealed containers, ambient temperature.\nNever store above 60 °C — additives break down.",
                "Skin: wash with soap + water. If injected under pressure — seek IMMEDIATE surgical review even if wound looks minor.",
                'Waste-oil contractor. Filter, then recycle base stock where possible.',
                '2025-08-01', $offset(-15),
            ],
            [
                'SDS-004', 'Engine Coolant (Ethylene Glycol 50/50)', 'CASTROL', 'Puma Energy TZ Ltd',
                '107-21-1', 'toxic',
                'Nitrile gloves, safety goggles',
                "Toxic if swallowed — sweet taste attracts children/animals.\nKidney damage on ingestion.\nMild skin irritant.",
                "Sealed labelled containers only.\nSeparate from potable water storage.\nKeep away from feed/food areas.",
                "Skin/eye: rinse thoroughly.\nIngestion: seek medical help IMMEDIATELY — treat as toxic exposure. Do not induce vomiting.",
                'Neutralise then licensed disposal only. Never to drain.',
                '2025-04-20', $offset(60),
            ],
            [
                'SDS-005', 'Battery Acid (Sulphuric 30%)', 'Chloride Exide', 'Chloride Exide Tanzania',
                '7664-93-9', 'corrosive',
                'Face shield, rubber gauntlets, apron, FR overalls, rubber boots',
                "STRONG CORROSIVE — causes severe burns on skin/eye contact.\nReacts violently with alkalis + metals.\nHydrogen gas hazard when charging (explosion risk).",
                "Ventilated battery room ONLY. Acid-resistant flooring.\nEye-wash + safety shower within 3 m.\nAcid on lower shelf, alkali (if any) upper — never above eye level.",
                "Skin: flush 20+ min under safety shower. Remove contaminated clothing.\nEye: irrigate 30 min continuous, call medic during transport.",
                'Neutralise with soda ash, licensed disposal. NEVER to drain.',
                '2025-01-15', $offset(-45),
            ],
            [
                'SDS-006', 'Compressed Oxygen (Industrial)', 'BOC / Linde', 'BOC Tanzania Ltd',
                '7782-44-7', 'oxidiser',
                'Face shield when opening valves, gloves free of oil/grease',
                "Strong oxidiser — accelerates combustion violently.\nOil/grease + O₂ = fire hazard.\nHigh-pressure gas — cylinder rocket risk if valve sheared.",
                "Upright, chained, valve caps in place.\nSeparate from flammable gases by 6 m or firewall.\nCool ventilated area, max 50 °C.",
                "Inhalation of pure O₂ prolonged: fresh air. Frostbite from LOX: warm slowly with water 40–42 °C.\nCall medic if breathing affected.",
                'Return empty cylinders to supplier. Do not vent to atmosphere near ignition sources.',
                '2025-05-01', $offset(200),
            ],
            [
                'SDS-007', 'Acetylene (Dissolved in Acetone)', 'BOC / Linde', 'BOC Tanzania Ltd',
                '74-86-2', 'flammable',
                'Face shield, welding gauntlets, FR overalls',
                "Extremely flammable gas. Explosive with air (2.5–82%).\nUnstable above 15 psi in free state — dissolved in acetone for transport.\nCopper alloy reaction — forms explosive acetylides.",
                "Upright, chained, valve caps.\nNever store or use in copper piping or fittings.\nSeparate 6 m from oxygen or firewall.",
                "Frostbite: warm slowly. Inhalation: fresh air, call medic if breathing affected.",
                'Return empty cylinders. Never puncture or incinerate.',
                '2025-05-01', $offset(200),
            ],
            [
                'SDS-008', 'WD-40 Multi-Use Aerosol', 'WD-40 Company', 'General hardware',
                null, 'flammable',
                'Nitrile gloves, safety goggles in enclosed spaces',
                "Aerosol — flammable propellant. Pressurised.\nAsphyxiation hazard in confined spaces.\nAvoid eye contact.",
                "Below 50 °C, out of direct sunlight. Never puncture or incinerate.",
                "Eye: rinse 10 min. Skin: wash. Inhalation: fresh air.",
                'Empty cans to metal recycling. Do not incinerate — even empty.',
                '2025-02-10', $offset(365),
            ],
            [
                'SDS-009', 'Isopropyl Alcohol (99%)', 'Sigma-Aldrich', 'Lab supply Ltd',
                '67-63-0', 'flammable',
                'Nitrile gloves, safety goggles',
                "Highly flammable liquid. Vapour heavier than air, can travel to ignition sources.\nEye and respiratory irritant.\nCNS depressant if inhaled in high concentration.",
                "Cool, ventilated, out of sunlight. Grounded metal cabinet.\nMax 20 L per fire zone.",
                "Skin: wash with soap + water. Eye: rinse 15 min.\nInhalation: fresh air.",
                'Small quantities: soak absorbent + landfill. Bulk: licensed solvent recycler.',
                '2025-07-01', $offset(90),
            ],
            [
                'SDS-010', 'Cement (Portland, dry powder)', 'Twiga / Simba', 'Local supplier',
                '65997-15-1', 'health',
                'Dust mask (P2/N95), safety goggles, gloves, long sleeves',
                "Alkaline dust — skin/eye/respiratory irritant.\nProlonged skin contact = cement burns (delayed onset, deep).\nInhalation = silicosis risk over long exposure.",
                "Dry, off-ground on pallets. Max 90 days storage — hardens with humidity.",
                "Skin: wash with plenty of water — check for delayed burns 24 h later.\nEye: rinse 15 min. Inhalation: fresh air.",
                'Waste cement to construction landfill only.',
                '2025-06-01', $offset(15),
            ],
        ];

        foreach ($rows as $r) {
            $this->table('sds')->insert([
                'tenant_id'     => $tenantId,
                'code'          => $r[0],
                'name'          => $r[1],
                'manufacturer'  => $r[2],
                'supplier'      => $r[3],
                'cas_number'    => $r[4],
                'hazard_class'  => $r[5],
                'ppe_required'  => $r[6],
                'hazards'       => $r[7],
                'storage_notes' => $r[8],
                'first_aid'     => $r[9],
                'disposal_notes'=> $r[10],
                'issued_at'     => $r[11],
                'review_at'     => $r[12],
            ])->saveData();
        }
    }
}
