-- =====================================================================
-- 37_complain.sql
-- Complaint
--
-- GENERATED by _gen/pack.py from ../step/. DO NOT EDIT -- edit the source
-- there and re-pack, or the sha256 in MANIFEST.md stops matching.
--
-- 13 table(s), 52 ledger step(s).
--
-- ⚠ IMPORT ORDER: 01_system.sql, then all seven 1x masters, then this file. Order among
--    transactions does not matter. Re-importing costs nothing.
--
-- ⚠ STOP ON THE FIRST ERROR. Do not use `mysql --force`, and do not tick any
--    "continue on error" box. Each step records itself in `_migration_ledger`
--    immediately after its statement runs, WITHOUT checking that the statement
--    succeeded -- that is inherited from step/, where run.sh guarantees a stop by
--    running mysql without --force. Continue past an error here and a step that
--    failed is marked applied: 99_finalize.sql will then seed `migrations`, and
--    `php artisan migrate` will skip the work still owed. Both default clients
--    stop on error; the danger is turning that off.
--
-- ⚠ phpMyAdmin: UNTICK "Allow the interruption of an import".
--    If it fires, the import resumes on a NEW CONNECTION: SQL_MODE reverts to the server
--    default and every @variable dies, mid-file. Two things then break. NO_ZERO_DATE is
--    back, so any ALTER that rebuilds a table holding '0000-00-00' fails with ERROR 1292.
--    And @step / @todo / @sql are NULL, so the guard around the next payload stops meaning
--    anything. The SET SQL_MODE before every unit below limits the damage when someone
--    forgets the checkbox; it does not replace unticking it.
--
--    (STRICT_TRANS_TABLES is forced for a third case -- a value too big for its new column
--    is CLAMPED silently rather than refused. Measured on the tree as it stands, no column
--    narrows: all 674 MODIFY COLUMNs widen or are no-ops. It stays forced because the next
--    regeneration is under no obligation to keep that true.)
--
-- ⚠ Take a full backup first. The `20_cleanup` steps change data and nothing here
--    reverses them. `../audit_bukanmain_before_migrate.sql` only reads.
-- =====================================================================

-- Menus this file serves (22 links):
--   /complain-types
--   /complaints
--   /complaints/all
--   /complaints/all-readonly
--   /complaints/all-report
--   /complaints/ceo
--   /complaints/close
--   /complaints/complete/accounting
--   /complaints/complete/cs
--   /complaints/complete/finance
--   /complaints/complete/logistic
--   /complaints/complete/pm
--   /complaints/complete/sm
--   /complaints/create
--   /complaints/create-others
--   /complaints/head-dept
--   /complaints/review/accounting
--   /complaints/review/cs
--   /complaints/review/finance
--   /complaints/review/logistic
--   /complaints/review/pm
--   /complaints/review/sm

-- --------------------------------------------------------------- prologue
-- run.sh sources step/_lib/session.sql for you. phpMyAdmin will not, so it is inlined.
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- Assert all four, not just the first. STRICT_TRANS_TABLES missing means out-of-range
-- values are clamped silently; NO_ZERO_DATE still present means any ALTER that rebuilds a
-- legacy table re-validates its '0000-00-00' rows and dies with ERROR 1292. The second is
-- the one that actually stops the migration, and it was not being checked.
SELECT IF(@@SQL_MODE LIKE '%STRICT_TRANS_TABLES%'
      AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
      AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
      AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
          'sql_mode OK - proceeding',
          (SELECT 'ABORT: sql_mode is wrong. Wanted STRICT_TRANS_TABLES + NO_AUTO_VALUE_ON_ZERO,'
           UNION ALL
           SELECT 'and NO_ZERO_DATE / NO_ZERO_IN_DATE OFF. The SET above should have done it.')
       ) AS preflight_sql_mode;

SET SESSION lock_wait_timeout = 60;
SET SESSION innodb_lock_wait_timeout = 60;

-- The ledger, copied verbatim from step/_lib/ledger.sql -- not restated, so the two
-- paths cannot disagree about its definition.
-- ---------------------------------------------------------------------
-- _lib/ledger.sql  --  the only thing here that is not in the source file
-- One row per applied step. This is the record that decides what a re-run skips,
-- what --status reports, and -- through the app-side gate -- which modules the
-- application will serve. It lives in the database on purpose: a file on one
-- operator's laptop drifts the moment someone runs a step from another machine.
--
-- Deliberately NOT in the project's PascalCase convention. It is an ops table, never
-- touched by Eloquent, and it should be visibly not-an-app-table.
--
-- `checksum` is the SHA-256 of the step's SQL payload -- the verbatim statements,
-- not the file -- so it cannot change when a comment above them is reworded.
-- _lib/steps.tsv carries the whole-file hashes for tamper detection.
--
-- ⚠ `step` IS ascii, AND THAT IS LOAD-BEARING. Every guard compares it against a
-- user variable, and a user variable carries the CONNECTION collation. Give this
-- column utf8mb4_unicode_ci and the very first step dies with ERROR 1267,
-- "Illegal mix of collations (utf8mb4_unicode_ci,IMPLICIT) and
-- (utf8mb4_0900_ai_ci,IMPLICIT) for operation '='" -- measured, that is exactly
-- how the first end-to-end run failed. ascii is a repertoire subset of latin1 and
-- of utf8mb4, so the server coerces it to whatever the connection is using,
-- whatever that turns out to be on the day. Step names are [a-z0-9_/] by
-- construction, so nothing is lost.
-- ---------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS `_migration_ledger` (
  `step`        varchar(191) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL,
  `applied_at`  datetime     NOT NULL,
  `checksum`    char(64)     NOT NULL,
  `duration_ms` int          NOT NULL,
  PRIMARY KEY (`step`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


-- --------------------------------------------------------------- preflight
-- 00_system/01_system.sql MUST already be applied. Every doc says so; until now nothing
-- enforced it, and the violation was silent for most of the tree: only three files break
-- without it (30_quotation and 40_budgetandtarget hit ERROR 1146 on a table 01_system
-- creates, and 99_finalize needs `migrations`). The other twenty import cleanly, record
-- their ledger rows, and leave a database that is half-migrated with nothing to say so.
--
-- 13 steps: the ALTER DATABASE plus the 12 CREATE TABLEs.
SET @sys_done = (SELECT COUNT(*) FROM `_migration_ledger` WHERE `step` LIKE '\_system/%');
SET @pf_sys = IF(@sys_done >= 13,
    'SELECT ''preflight: 00_system is applied'' AS preflight_system',
    'SELECT `ABORT: import 00_system/01_system.sql first. It runs the ALTER DATABASE and creates the 12 new tables that everything here assumes exist.`');
PREPARE _pf FROM @pf_sys; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- --------------------------------------------------------------- preflight
-- WAS THIS DATABASE MIGRATED FROM A DIFFERENT VERSION OF THIS FILE?
--
-- `_migration_ledger.checksum` is the SHA-256 of each step's payload. It is written 632
-- times across the tree and, until this block existed, read never -- so a corrected payload
-- re-issued under the same step name was skipped forever on any database that had recorded
-- the old one, silently and permanently.
SELECT COUNT(*) INTO @ck_bad FROM `_migration_ledger`
 WHERE `step` IN ('complain/10_alter', 'complain/20_cleanup', 'complain/30_assert', 'complain/40_fk', 'complainassignment/10_alter', 'complainassignment/20_cleanup', 'complainassignment/30_assert', 'complainassignment/40_fk', 'complaindetails/10_alter', 'complaindetails/20_cleanup', 'complaindetails/30_assert', 'complaindetails/40_fk', 'complaindetailsaction/10_alter', 'complaindetailsaction/20_cleanup', 'complaindetailsaction/30_assert', 'complaindetailsaction/40_fk', 'complaindetailsactionassignment/10_alter', 'complaindetailsactionassignment/20_cleanup', 'complaindetailsactionassignment/30_assert', 'complaindetailsactionassignment/40_fk', 'complaindetailsassignment/10_alter', 'complaindetailsassignment/20_cleanup', 'complaindetailsassignment/30_assert', 'complaindetailsassignment/40_fk', 'complainitem/10_alter', 'complainitem/20_cleanup', 'complainitem/30_assert', 'complainitem/40_fk', 'complainitemassignment/10_alter', 'complainitemassignment/20_cleanup', 'complainitemassignment/30_assert', 'complainitemassignment/40_fk', 'complainitemdetails/10_alter', 'complainitemdetails/20_cleanup', 'complainitemdetails/30_assert', 'complainitemdetails/40_fk', 'complainitemdetailsaction/10_alter', 'complainitemdetailsaction/20_cleanup', 'complainitemdetailsaction/30_assert', 'complainitemdetailsaction/40_fk', 'complainitemdetailsactionassignment/10_alter', 'complainitemdetailsactionassignment/20_cleanup', 'complainitemdetailsactionassignment/30_assert', 'complainitemdetailsactionassignment/40_fk', 'complainitemdetailslot/10_alter', 'complainitemdetailslot/20_cleanup', 'complainitemdetailslot/30_assert', 'complainitemdetailslot/40_fk', 'complainitemdetailslotassignment/10_alter', 'complainitemdetailslotassignment/20_cleanup', 'complainitemdetailslotassignment/30_assert', 'complainitemdetailslotassignment/40_fk')
   AND CONCAT(`step`, ':', `checksum`) NOT IN ('complain/10_alter:b1539bafc3e53143d87d2758fc4c110362f4207bb144f62692839a28fd676707', 'complain/20_cleanup:d4ecbce2426c004dbd13bfe98165fd6dfd427e8c437c9b21023c58689aa3ebc1', 'complain/30_assert:cd76fcc84772376c3c75978fd40b328fa66dcd083bbb0304a5f24c458e7168cd', 'complain/40_fk:998f0300aa1ba6d448bf338a8fadc25b0dd417efa170c7acac52b7275fcf1fd1', 'complainassignment/10_alter:18b832a43d9e68f902df8416535f6eaac02fcaf99300b3d6442181d0c0c20aa7', 'complainassignment/20_cleanup:0101abbcb8f5f024fc5be27904fc731be2346d36ec8b1d05e61e2c6243555ae5', 'complainassignment/30_assert:abb294f34bfc5f86c9e24c74c82a40f67ec85641e982664ad83bd0c843542f5c', 'complainassignment/40_fk:4366b05eab5cce2804f962a1471d28522e0a4ea09fce38d9a69568892768d6ad', 'complaindetails/10_alter:0162983efe14343a74c42d0d77e01d9923ce35b597ba122fdfa3641ca64a50fc', 'complaindetails/20_cleanup:8e8419d11a515cd8e2058b9db9eca844fc3b5b9b798df116d3eb96c9327f2600', 'complaindetails/30_assert:67c89be6c68dda9da3c1719eaa92af385f51ed8fdae7f62e9dd2d1b9700fb491', 'complaindetails/40_fk:ab066a1a50664d487d435136014c65802c57b54aac1049aa7aba6dbce5a80b0e', 'complaindetailsaction/10_alter:809cfe6975f27594ba874040ddbf197d31abdfc019c1e09eb31b8e4358278dfb', 'complaindetailsaction/20_cleanup:ae86e096c73a14c957550623598d2e5fcbff7d8a49d3290f6fb5e6e902afc8c8', 'complaindetailsaction/30_assert:974f8984d08315b712949712d61164143cbf59b530618c5f6220a3f2b3fb92f2', 'complaindetailsaction/40_fk:62b15f6c91564a213711481b9605a59fab42382491fbedcd2ad25eab80b7815d', 'complaindetailsactionassignment/10_alter:964d9a9d18db39de964f11680aa876a084513db38725a7683aa0daa0f4bd0ab2', 'complaindetailsactionassignment/20_cleanup:1b1e9f5066da30afa5dcdf8e20809b7be336f19550c379c1e31839e62aae0063', 'complaindetailsactionassignment/30_assert:01045a3443a65b69af55dc17f4284b0027b1a64acb5f8c3757662b8375847b99', 'complaindetailsactionassignment/40_fk:834820e4696dd7843ffc98d009798b0251dcce6fba417ee53c4fa357486c0454', 'complaindetailsassignment/10_alter:3711b5eef6b30766cb9e8d140bb60a15d1f338af8d7802c06916d4a60756feaf', 'complaindetailsassignment/20_cleanup:de7c0085b369752a936bcf5ba7240b131d551011bc95b1fe5d2e88cb1ffaaa8a', 'complaindetailsassignment/30_assert:49b2f6ecaae711570578fe6cdf0ef82ace8223ecaa70f03428a93c8d42087b5a', 'complaindetailsassignment/40_fk:001fdc8957538190d1115b8ea58583dda3af9d1596ff6862e68c917530b4d2f7', 'complainitem/10_alter:840bf2f53a1c0f86d0c3dfdc9fbbcdd0c7ed1dfebb7707c6a4893caaf6292723', 'complainitem/20_cleanup:915863db11343dfe0e15bf8dd14aa104ff9f5f050882f6bcff2fd5f54b36c95a', 'complainitem/30_assert:83017f74a6cc83bdad5aab42cc5b815bb6df6ba032a01d68ced40aa57469b477', 'complainitem/40_fk:6c58801320b6cdc1df13c46b31686f97cf3d2a8bc4fc295c6da2161c0f8e957f', 'complainitemassignment/10_alter:ffbeb3a2a5902415c40c77d184e143ab47453c905cb9852010513be78a33499c', 'complainitemassignment/20_cleanup:0682313f9440046d4472c536b5b5a53bb0118b02b5f9ee491389e0dea2a76fd2', 'complainitemassignment/30_assert:9624adbd3a49dacf49852caa03bbd8829387de017353695089f2575255a3e7dd', 'complainitemassignment/40_fk:4e4c95afe9380c6fe1080df39f9351ae39e839f954470ca87f9aeffd08930e76', 'complainitemdetails/10_alter:2933f23d1b834334a8a750db3ba869dbb6ca00e14421f24d5ac433c5e515cfd5', 'complainitemdetails/20_cleanup:afee15b35d8559ce9e98f7d3fcf3bf5a2f155d1a2d952989b7322169e0b83513', 'complainitemdetails/30_assert:6609dfb017eed483e282bb43b5ce33769a7a763e75c61ce02f49c1b5f61fbd6f', 'complainitemdetails/40_fk:2f4a24f538ebd62287d90bda9db7bdc598e92d684138ac686d3a063b665560a6', 'complainitemdetailsaction/10_alter:edd774041a104f2791145a98b801de7607f3823ee9685f45264f0d16ae65f119', 'complainitemdetailsaction/20_cleanup:e3b9c6c4e8c176c4fd5c82178d025c01f7a8e9375a388673dbff7af4e3955212', 'complainitemdetailsaction/30_assert:fd1b4b4e0d761e977713f186c2ddc50a35f5da50b2842346481b0e218c046560', 'complainitemdetailsaction/40_fk:9cf292eee87f71f1fcaaa7f48f0d963c40b315a993629337358f17b0c13f666d', 'complainitemdetailsactionassignment/10_alter:57d3483ccfb6f9a44b6e9ae5e75768f11a0a80bfb63789e0cc9a987b49e49da8', 'complainitemdetailsactionassignment/20_cleanup:f1a14bd42cec07ec4029c2d1941aa944adbb05792c736a87f6f28aa2b371d1f4', 'complainitemdetailsactionassignment/30_assert:0e125f004a7fd41918c3ad8ee648ce90faf93fe2514d3f491353d801263c636e', 'complainitemdetailsactionassignment/40_fk:f985964d8f3aa14181382811d017780f9985890a5e218428c12242719d463295', 'complainitemdetailslot/10_alter:cd1aca19ebab1cca4f1cb7bc55168e682ab87cc08c17b2e8bdf4a155c0596236', 'complainitemdetailslot/20_cleanup:425a9af853cc594e83cc63c51a899fc5eb47cd127f2342c62da40547c725202b', 'complainitemdetailslot/30_assert:5fba3fc71d1cc080251506bdda5239d76f354721ad88d629c54c3d2807073930', 'complainitemdetailslot/40_fk:448741452fb14f76bf0d821c42780e6c0c4f01a395dfa428f70c99e099bf8cc2', 'complainitemdetailslotassignment/10_alter:c872d4740304323c1612965ecbe6b9bfc882bac49ff5b396b3d9735fde3673f7', 'complainitemdetailslotassignment/20_cleanup:03742f4950c1193920e1b73304941ead95cb4e6e34b508f2e69b304e69102a05', 'complainitemdetailslotassignment/30_assert:ed54d7a2440d7118729b4010b685d723b5c6b5503a235aae9d6cbc5e9bb5512e', 'complainitemdetailslotassignment/40_fk:de71d1b745568bd2cb3003a27406e4031421534877950183f691d20a4185150c');
SET @pf_ck = IF(@ck_bad = 0,
    'SELECT ''preflight: ledger matches this file'' AS preflight_checksum',
    CONCAT('SELECT `ABORT: ', @ck_bad, ' step(s) here were applied from a DIFFERENT version of this file. Their payloads changed. Compare before re-importing; do not delete ledger rows blindly.`'));
PREPARE _pf FROM @pf_ck; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- ---------------------------------------------------------------------
-- unit: complain    (transaction)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complain/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complain/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complain`
  MODIFY COLUMN `ComplainStatusID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainTypeID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainReasonID` int DEFAULT NULL,
  MODIFY COLUMN `DivisionID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyCPID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `UserIDSales` int DEFAULT NULL,
  ADD INDEX `complain_CompanyCPID` (`CompanyCPID`),
  ADD INDEX `complain_CompanyID` (`CompanyID`),
  ADD INDEX `complain_ComplainReasonID` (`ComplainReasonID`),
  ADD INDEX `complain_ComplainTypeID` (`ComplainTypeID`),
  ADD INDEX `complain_DivisionID` (`DivisionID`),
  ADD INDEX `complain_UserIDInput` (`UserIDInput`),
  ADD INDEX `complain_UserIDSales` (`UserIDSales`),
  ADD INDEX `ComplainStatusID` (`ComplainStatusID`,`ComplainTypeID`,`DivisionID`,`CompanyID`,`CompanyCPID`,`UserIDInput`,`UserIDSales`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'b1539bafc3e53143d87d2758fc4c110362f4207bb144f62692839a28fd676707', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complain/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complain/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complain` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCPID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `complainreason` p2 ON c.`ComplainReasonID` = p2.`ID`
  LEFT JOIN `complainstatus` p3 ON c.`ComplainStatusID` = p3.`ID`
  LEFT JOIN `complaintype` p4 ON c.`ComplainTypeID` = p4.`ID`
  LEFT JOIN `division` p5 ON c.`DivisionID` = p5.`ID`
  LEFT JOIN `users` p6 ON c.`UserIDInput` = p6.`ID`
  LEFT JOIN `users` p7 ON c.`UserIDSales` = p7.`ID`
   SET
       c.`CompanyCPID` = IF((c.`CompanyCPID` IS NOT NULL AND (c.`CompanyCPID` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyCPID`),
       c.`CompanyID` = IF((c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL)), NULL, c.`CompanyID`),
       c.`ComplainReasonID` = IF((c.`ComplainReasonID` IS NOT NULL AND (c.`ComplainReasonID` = 0 OR p2.`ID` IS NULL)), NULL, c.`ComplainReasonID`),
       c.`ComplainStatusID` = IF((c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p3.`ID` IS NULL)), NULL, c.`ComplainStatusID`),
       c.`ComplainTypeID` = IF((c.`ComplainTypeID` IS NOT NULL AND (c.`ComplainTypeID` = 0 OR p4.`ID` IS NULL)), NULL, c.`ComplainTypeID`),
       c.`DivisionID` = IF((c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p5.`ID` IS NULL)), NULL, c.`DivisionID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p6.`ID` IS NULL)), NULL, c.`UserIDInput`),
       c.`UserIDSales` = IF((c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p7.`ID` IS NULL)), NULL, c.`UserIDSales`)
 WHERE  (c.`CompanyCPID` IS NOT NULL AND (c.`CompanyCPID` = 0 OR p0.`ID` IS NULL))
    OR (c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL))
    OR (c.`ComplainReasonID` IS NOT NULL AND (c.`ComplainReasonID` = 0 OR p2.`ID` IS NULL))
    OR (c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p3.`ID` IS NULL))
    OR (c.`ComplainTypeID` IS NOT NULL AND (c.`ComplainTypeID` = 0 OR p4.`ID` IS NULL))
    OR (c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p5.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p6.`ID` IS NULL))
    OR (c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p7.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'd4ecbce2426c004dbd13bfe98165fd6dfd427e8c437c9b21023c58689aa3ebc1', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complain/30_assert  --  source section 7b
-- Orphan assertion over this table's 8 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complain/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complain` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCPID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `complainreason` p2 ON c.`ComplainReasonID` = p2.`ID`
  LEFT JOIN `complainstatus` p3 ON c.`ComplainStatusID` = p3.`ID`
  LEFT JOIN `complaintype` p4 ON c.`ComplainTypeID` = p4.`ID`
  LEFT JOIN `division` p5 ON c.`DivisionID` = p5.`ID`
  LEFT JOIN `users` p6 ON c.`UserIDInput` = p6.`ID`
  LEFT JOIN `users` p7 ON c.`UserIDSales` = p7.`ID`
 WHERE  (c.`CompanyCPID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`CompanyID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`ComplainReasonID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`ComplainStatusID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`ComplainTypeID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`DivisionID` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`UserIDSales` IS NOT NULL AND p7.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complain: orphan check OK - 0 rows across 8 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complain` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'cd76fcc84772376c3c75978fd40b328fa66dcd083bbb0304a5f24c458e7168cd', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complain/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complain/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complain`
  ADD CONSTRAINT `complain_CompanyCPID` FOREIGN KEY (`CompanyCPID`) REFERENCES `companycp` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complain_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complain_ComplainReasonID` FOREIGN KEY (`ComplainReasonID`) REFERENCES `complainreason` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complain_ComplainStatusID` FOREIGN KEY (`ComplainStatusID`) REFERENCES `complainstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complain_ComplainTypeID` FOREIGN KEY (`ComplainTypeID`) REFERENCES `complaintype` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complain_DivisionID` FOREIGN KEY (`DivisionID`) REFERENCES `division` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complain_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complain_UserIDSales` FOREIGN KEY (`UserIDSales`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '998f0300aa1ba6d448bf338a8fadc25b0dd417efa170c7acac52b7275fcf1fd1', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: complainassignment    (detail, owned by complain)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complainassignment/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complainassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainassignment`
  MODIFY COLUMN `Comment` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  MODIFY COLUMN `ComplainID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainStatusID` int DEFAULT NULL,
  MODIFY COLUMN `UserID` int DEFAULT NULL,
  ADD INDEX `complainassignment_ComplainStatusID` (`ComplainStatusID`),
  ADD INDEX `complainassignment_UserID` (`UserID`),
  ADD INDEX `ComplainID` (`ComplainID`,`ComplainStatusID`,`UserID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '18b832a43d9e68f902df8416535f6eaac02fcaf99300b3d6442181d0c0c20aa7', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainassignment/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complainassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complainassignment` c
  LEFT JOIN `complain` p0 ON c.`ComplainID` = p0.`ID`
  LEFT JOIN `complainstatus` p1 ON c.`ComplainStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserID` = p2.`ID`
   SET
       c.`ComplainID` = IF((c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ComplainID`),
       c.`ComplainStatusID` = IF((c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ComplainStatusID`),
       c.`UserID` = IF((c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserID`)
 WHERE  (c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p2.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '0101abbcb8f5f024fc5be27904fc731be2346d36ec8b1d05e61e2c6243555ae5', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complainassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 3 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complainassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complainassignment` c
  LEFT JOIN `complain` p0 ON c.`ComplainID` = p0.`ID`
  LEFT JOIN `complainstatus` p1 ON c.`ComplainStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserID` = p2.`ID`
 WHERE  (c.`ComplainID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ComplainStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`UserID` IS NOT NULL AND p2.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complainassignment: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complainassignment` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'abb294f34bfc5f86c9e24c74c82a40f67ec85641e982664ad83bd0c843542f5c', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainassignment/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complainassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainassignment`
  ADD CONSTRAINT `complainassignment_ComplainID` FOREIGN KEY (`ComplainID`) REFERENCES `complain` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainassignment_ComplainStatusID` FOREIGN KEY (`ComplainStatusID`) REFERENCES `complainstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainassignment_UserID` FOREIGN KEY (`UserID`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '4366b05eab5cce2804f962a1471d28522e0a4ea09fce38d9a69568892768d6ad', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: complaindetails    (detail, owned by complain)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complaindetails/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complaindetails/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaindetails`
  MODIFY COLUMN `QuantityPacking` decimal(20,5) NOT NULL,
  MODIFY COLUMN `ComplainQuantity` decimal(20,5) NOT NULL,
  MODIFY COLUMN `ComplainID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainDetailsStatusID` int DEFAULT NULL,
  MODIFY COLUMN `PrincipalID` int DEFAULT NULL,
  MODIFY COLUMN `BarangID` int DEFAULT NULL,
  MODIFY COLUMN `ApplicationID` int DEFAULT NULL,
  MODIFY COLUMN `SatuanPackingID` int DEFAULT NULL,
  MODIFY COLUMN `SatuanComplainQuantityID` int DEFAULT NULL,
  MODIFY COLUMN `SatuanUnitPriceUSD` int DEFAULT NULL,
  ADD INDEX `complaindetails_ApplicationID` (`ApplicationID`),
  ADD INDEX `complaindetails_BarangID` (`BarangID`),
  ADD INDEX `complaindetails_ComplainDetailsStatusID` (`ComplainDetailsStatusID`),
  ADD INDEX `complaindetails_PrincipalID` (`PrincipalID`),
  ADD INDEX `complaindetails_SatuanComplainQuantityID` (`SatuanComplainQuantityID`),
  ADD INDEX `complaindetails_SatuanPackingID` (`SatuanPackingID`),
  ADD INDEX `complaindetails_SatuanUnitPriceUSD` (`SatuanUnitPriceUSD`),
  ADD INDEX `ComplainID` (`ComplainID`,`ComplainDetailsStatusID`,`PrincipalID`,`BarangID`,`ApplicationID`,`SatuanPackingID`,`BarangListID`,`SatuanComplainQuantityID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '0162983efe14343a74c42d0d77e01d9923ce35b597ba122fdfa3641ca64a50fc', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaindetails/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complaindetails/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complaindetails` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`BarangID` = p1.`ID`
  LEFT JOIN `complaindetailsstatus` p2 ON c.`ComplainDetailsStatusID` = p2.`ID`
  LEFT JOIN `complain` p3 ON c.`ComplainID` = p3.`ID`
  LEFT JOIN `principal` p4 ON c.`PrincipalID` = p4.`ID`
  LEFT JOIN `satuan` p5 ON c.`SatuanComplainQuantityID` = p5.`ID`
  LEFT JOIN `quotationpack` p6 ON c.`SatuanPackingID` = p6.`ID`
  LEFT JOIN `satuan` p7 ON c.`SatuanUnitPriceUSD` = p7.`ID`
   SET
       c.`ApplicationID` = IF((c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ApplicationID`),
       c.`BarangID` = IF((c.`BarangID` IS NOT NULL AND (c.`BarangID` = 0 OR p1.`ID` IS NULL)), NULL, c.`BarangID`),
       c.`ComplainDetailsStatusID` = IF((c.`ComplainDetailsStatusID` IS NOT NULL AND (c.`ComplainDetailsStatusID` = 0 OR p2.`ID` IS NULL)), NULL, c.`ComplainDetailsStatusID`),
       c.`ComplainID` = IF((c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p3.`ID` IS NULL)), NULL, c.`ComplainID`),
       c.`PrincipalID` = IF((c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p4.`ID` IS NULL)), NULL, c.`PrincipalID`),
       c.`SatuanComplainQuantityID` = IF((c.`SatuanComplainQuantityID` IS NOT NULL AND (c.`SatuanComplainQuantityID` = 0 OR p5.`ID` IS NULL)), NULL, c.`SatuanComplainQuantityID`),
       c.`SatuanPackingID` = IF((c.`SatuanPackingID` IS NOT NULL AND (c.`SatuanPackingID` = 0 OR p6.`ID` IS NULL)), NULL, c.`SatuanPackingID`),
       c.`SatuanUnitPriceUSD` = IF((c.`SatuanUnitPriceUSD` IS NOT NULL AND (c.`SatuanUnitPriceUSD` = 0 OR p7.`ID` IS NULL)), NULL, c.`SatuanUnitPriceUSD`)
 WHERE  (c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL))
    OR (c.`BarangID` IS NOT NULL AND (c.`BarangID` = 0 OR p1.`ID` IS NULL))
    OR (c.`ComplainDetailsStatusID` IS NOT NULL AND (c.`ComplainDetailsStatusID` = 0 OR p2.`ID` IS NULL))
    OR (c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p3.`ID` IS NULL))
    OR (c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p4.`ID` IS NULL))
    OR (c.`SatuanComplainQuantityID` IS NOT NULL AND (c.`SatuanComplainQuantityID` = 0 OR p5.`ID` IS NULL))
    OR (c.`SatuanPackingID` IS NOT NULL AND (c.`SatuanPackingID` = 0 OR p6.`ID` IS NULL))
    OR (c.`SatuanUnitPriceUSD` IS NOT NULL AND (c.`SatuanUnitPriceUSD` = 0 OR p7.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '8e8419d11a515cd8e2058b9db9eca844fc3b5b9b798df116d3eb96c9327f2600', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complaindetails/30_assert  --  source section 7b
-- Orphan assertion over this table's 8 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complaindetails/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complaindetails` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`BarangID` = p1.`ID`
  LEFT JOIN `complaindetailsstatus` p2 ON c.`ComplainDetailsStatusID` = p2.`ID`
  LEFT JOIN `complain` p3 ON c.`ComplainID` = p3.`ID`
  LEFT JOIN `principal` p4 ON c.`PrincipalID` = p4.`ID`
  LEFT JOIN `satuan` p5 ON c.`SatuanComplainQuantityID` = p5.`ID`
  LEFT JOIN `quotationpack` p6 ON c.`SatuanPackingID` = p6.`ID`
  LEFT JOIN `satuan` p7 ON c.`SatuanUnitPriceUSD` = p7.`ID`
 WHERE  (c.`ApplicationID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`BarangID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`ComplainDetailsStatusID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`ComplainID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`PrincipalID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`SatuanComplainQuantityID` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`SatuanPackingID` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`SatuanUnitPriceUSD` IS NOT NULL AND p7.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complaindetails: orphan check OK - 0 rows across 8 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complaindetails` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '67c89be6c68dda9da3c1719eaa92af385f51ed8fdae7f62e9dd2d1b9700fb491', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaindetails/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complaindetails/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaindetails`
  ADD CONSTRAINT `complaindetails_ApplicationID` FOREIGN KEY (`ApplicationID`) REFERENCES `application` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetails_BarangID` FOREIGN KEY (`BarangID`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetails_ComplainDetailsStatusID` FOREIGN KEY (`ComplainDetailsStatusID`) REFERENCES `complaindetailsstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetails_ComplainID` FOREIGN KEY (`ComplainID`) REFERENCES `complain` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetails_PrincipalID` FOREIGN KEY (`PrincipalID`) REFERENCES `principal` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetails_SatuanComplainQuantityID` FOREIGN KEY (`SatuanComplainQuantityID`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetails_SatuanPackingID` FOREIGN KEY (`SatuanPackingID`) REFERENCES `quotationpack` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetails_SatuanUnitPriceUSD` FOREIGN KEY (`SatuanUnitPriceUSD`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'ab066a1a50664d487d435136014c65802c57b54aac1049aa7aba6dbce5a80b0e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: complaindetailsaction    (detail, owned by complain)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complaindetailsaction/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complaindetailsaction/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaindetailsaction`
  MODIFY COLUMN `ComplainID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainDetailsID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainDetailsStatusID` int DEFAULT NULL,
  MODIFY COLUMN `DepartmentID` int DEFAULT NULL,
  MODIFY COLUMN `UserID` int DEFAULT NULL,
  ADD INDEX `complaindetailsaction_ComplainDetailsID` (`ComplainDetailsID`),
  ADD INDEX `complaindetailsaction_ComplainDetailsStatusID` (`ComplainDetailsStatusID`),
  ADD INDEX `complaindetailsaction_DepartmentID` (`DepartmentID`),
  ADD INDEX `complaindetailsaction_UserID` (`UserID`),
  ADD INDEX `ComplainID` (`ComplainID`,`ComplainDetailsID`,`ComplainDetailsStatusID`,`DepartmentID`,`UserID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '809cfe6975f27594ba874040ddbf197d31abdfc019c1e09eb31b8e4358278dfb', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaindetailsaction/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complaindetailsaction/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complaindetailsaction` c
  LEFT JOIN `complaindetails` p0 ON c.`ComplainDetailsID` = p0.`ID`
  LEFT JOIN `complaindetailsstatus` p1 ON c.`ComplainDetailsStatusID` = p1.`ID`
  LEFT JOIN `complain` p2 ON c.`ComplainID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserID` = p3.`ID`
   SET
       c.`ComplainDetailsID` = IF((c.`ComplainDetailsID` IS NOT NULL AND (c.`ComplainDetailsID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ComplainDetailsID`),
       c.`ComplainDetailsStatusID` = IF((c.`ComplainDetailsStatusID` IS NOT NULL AND (c.`ComplainDetailsStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ComplainDetailsStatusID`),
       c.`ComplainID` = IF((c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p2.`ID` IS NULL)), NULL, c.`ComplainID`),
       c.`UserID` = IF((c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p3.`ID` IS NULL)), NULL, c.`UserID`)
 WHERE  (c.`ComplainDetailsID` IS NOT NULL AND (c.`ComplainDetailsID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ComplainDetailsStatusID` IS NOT NULL AND (c.`ComplainDetailsStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p2.`ID` IS NULL))
    OR (c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p3.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'ae86e096c73a14c957550623598d2e5fcbff7d8a49d3290f6fb5e6e902afc8c8', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complaindetailsaction/30_assert  --  source section 7b
-- Orphan assertion over this table's 4 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complaindetailsaction/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complaindetailsaction` c
  LEFT JOIN `complaindetails` p0 ON c.`ComplainDetailsID` = p0.`ID`
  LEFT JOIN `complaindetailsstatus` p1 ON c.`ComplainDetailsStatusID` = p1.`ID`
  LEFT JOIN `complain` p2 ON c.`ComplainID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserID` = p3.`ID`
 WHERE  (c.`ComplainDetailsID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ComplainDetailsStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`ComplainID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`UserID` IS NOT NULL AND p3.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complaindetailsaction: orphan check OK - 0 rows across 4 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complaindetailsaction` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '974f8984d08315b712949712d61164143cbf59b530618c5f6220a3f2b3fb92f2', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaindetailsaction/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complaindetailsaction/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaindetailsaction`
  ADD CONSTRAINT `complaindetailsaction_ComplainDetailsID` FOREIGN KEY (`ComplainDetailsID`) REFERENCES `complaindetails` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetailsaction_ComplainDetailsStatusID` FOREIGN KEY (`ComplainDetailsStatusID`) REFERENCES `complaindetailsstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetailsaction_ComplainID` FOREIGN KEY (`ComplainID`) REFERENCES `complain` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetailsaction_UserID` FOREIGN KEY (`UserID`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '62b15f6c91564a213711481b9605a59fab42382491fbedcd2ad25eab80b7815d', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: complaindetailsactionassignment    (detail, owned by complain)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complaindetailsactionassignment/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complaindetailsactionassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaindetailsactionassignment`
  MODIFY COLUMN `ComplainDetailsActionID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainDetailsID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainDetailsStatusID` int DEFAULT NULL,
  MODIFY COLUMN `DepartmentID` int DEFAULT NULL,
  MODIFY COLUMN `UserID` int DEFAULT NULL,
  ADD INDEX `complaindetailsactionassignment_ComplainDetailsID` (`ComplainDetailsID`),
  ADD INDEX `complaindetailsactionassignment_ComplainDetailsStatusID` (`ComplainDetailsStatusID`),
  ADD INDEX `complaindetailsactionassignment_ComplainID` (`ComplainID`),
  ADD INDEX `complaindetailsactionassignment_DepartmentID` (`DepartmentID`),
  ADD INDEX `complaindetailsactionassignment_UserID` (`UserID`),
  ADD INDEX `ComplainDetailsActionID` (`ComplainDetailsActionID`,`ComplainID`,`ComplainDetailsID`,`ComplainDetailsStatusID`,`DepartmentID`,`UserID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '964d9a9d18db39de964f11680aa876a084513db38725a7683aa0daa0f4bd0ab2', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaindetailsactionassignment/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complaindetailsactionassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complaindetailsactionassignment` c
  LEFT JOIN `complaindetailsaction` p0 ON c.`ComplainDetailsActionID` = p0.`ID`
  LEFT JOIN `complaindetails` p1 ON c.`ComplainDetailsID` = p1.`ID`
  LEFT JOIN `complaindetailsstatus` p2 ON c.`ComplainDetailsStatusID` = p2.`ID`
  LEFT JOIN `complain` p3 ON c.`ComplainID` = p3.`ID`
  LEFT JOIN `users` p4 ON c.`UserID` = p4.`ID`
   SET
       c.`ComplainDetailsActionID` = IF((c.`ComplainDetailsActionID` IS NOT NULL AND (c.`ComplainDetailsActionID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ComplainDetailsActionID`),
       c.`ComplainDetailsID` = IF((c.`ComplainDetailsID` IS NOT NULL AND (c.`ComplainDetailsID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ComplainDetailsID`),
       c.`ComplainDetailsStatusID` = IF((c.`ComplainDetailsStatusID` IS NOT NULL AND (c.`ComplainDetailsStatusID` = 0 OR p2.`ID` IS NULL)), NULL, c.`ComplainDetailsStatusID`),
       c.`ComplainID` = IF((c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p3.`ID` IS NULL)), NULL, c.`ComplainID`),
       c.`UserID` = IF((c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p4.`ID` IS NULL)), NULL, c.`UserID`)
 WHERE  (c.`ComplainDetailsActionID` IS NOT NULL AND (c.`ComplainDetailsActionID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ComplainDetailsID` IS NOT NULL AND (c.`ComplainDetailsID` = 0 OR p1.`ID` IS NULL))
    OR (c.`ComplainDetailsStatusID` IS NOT NULL AND (c.`ComplainDetailsStatusID` = 0 OR p2.`ID` IS NULL))
    OR (c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p3.`ID` IS NULL))
    OR (c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p4.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '1b1e9f5066da30afa5dcdf8e20809b7be336f19550c379c1e31839e62aae0063', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complaindetailsactionassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 5 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complaindetailsactionassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complaindetailsactionassignment` c
  LEFT JOIN `complaindetailsaction` p0 ON c.`ComplainDetailsActionID` = p0.`ID`
  LEFT JOIN `complaindetails` p1 ON c.`ComplainDetailsID` = p1.`ID`
  LEFT JOIN `complaindetailsstatus` p2 ON c.`ComplainDetailsStatusID` = p2.`ID`
  LEFT JOIN `complain` p3 ON c.`ComplainID` = p3.`ID`
  LEFT JOIN `users` p4 ON c.`UserID` = p4.`ID`
 WHERE  (c.`ComplainDetailsActionID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ComplainDetailsID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`ComplainDetailsStatusID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`ComplainID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`UserID` IS NOT NULL AND p4.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complaindetailsactionassignment: orphan check OK - 0 rows across 5 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complaindetailsactionassignment` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '01045a3443a65b69af55dc17f4284b0027b1a64acb5f8c3757662b8375847b99', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaindetailsactionassignment/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complaindetailsactionassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaindetailsactionassignment`
  ADD CONSTRAINT `complaindetailsactionassignment_ComplainDetailsActionID` FOREIGN KEY (`ComplainDetailsActionID`) REFERENCES `complaindetailsaction` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetailsactionassignment_ComplainDetailsID` FOREIGN KEY (`ComplainDetailsID`) REFERENCES `complaindetails` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetailsactionassignment_ComplainDetailsStatusID` FOREIGN KEY (`ComplainDetailsStatusID`) REFERENCES `complaindetailsstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetailsactionassignment_ComplainID` FOREIGN KEY (`ComplainID`) REFERENCES `complain` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetailsactionassignment_UserID` FOREIGN KEY (`UserID`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '834820e4696dd7843ffc98d009798b0251dcce6fba417ee53c4fa357486c0454', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: complaindetailsassignment    (detail, owned by complain)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complaindetailsassignment/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complaindetailsassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaindetailsassignment`
  MODIFY COLUMN `ComplainID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainDetailsID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainDetailsStatusID` int DEFAULT NULL,
  MODIFY COLUMN `DepartmentID` int DEFAULT NULL,
  MODIFY COLUMN `UserID` int DEFAULT NULL,
  ADD INDEX `complaindetailsassignment_ComplainDetailsID` (`ComplainDetailsID`),
  ADD INDEX `complaindetailsassignment_ComplainDetailsStatusID` (`ComplainDetailsStatusID`),
  ADD INDEX `complaindetailsassignment_DepartmentID` (`DepartmentID`),
  ADD INDEX `complaindetailsassignment_UserID` (`UserID`),
  ADD INDEX `ComplainID` (`ComplainID`,`ComplainDetailsID`,`ComplainDetailsStatusID`,`DepartmentID`,`UserID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '3711b5eef6b30766cb9e8d140bb60a15d1f338af8d7802c06916d4a60756feaf', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaindetailsassignment/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complaindetailsassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complaindetailsassignment` c
  LEFT JOIN `complaindetails` p0 ON c.`ComplainDetailsID` = p0.`ID`
  LEFT JOIN `complaindetailsstatus` p1 ON c.`ComplainDetailsStatusID` = p1.`ID`
  LEFT JOIN `complain` p2 ON c.`ComplainID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserID` = p3.`ID`
   SET
       c.`ComplainDetailsID` = IF((c.`ComplainDetailsID` IS NOT NULL AND (c.`ComplainDetailsID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ComplainDetailsID`),
       c.`ComplainDetailsStatusID` = IF((c.`ComplainDetailsStatusID` IS NOT NULL AND (c.`ComplainDetailsStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ComplainDetailsStatusID`),
       c.`ComplainID` = IF((c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p2.`ID` IS NULL)), NULL, c.`ComplainID`),
       c.`UserID` = IF((c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p3.`ID` IS NULL)), NULL, c.`UserID`)
 WHERE  (c.`ComplainDetailsID` IS NOT NULL AND (c.`ComplainDetailsID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ComplainDetailsStatusID` IS NOT NULL AND (c.`ComplainDetailsStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p2.`ID` IS NULL))
    OR (c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p3.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'de7c0085b369752a936bcf5ba7240b131d551011bc95b1fe5d2e88cb1ffaaa8a', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complaindetailsassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 4 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complaindetailsassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complaindetailsassignment` c
  LEFT JOIN `complaindetails` p0 ON c.`ComplainDetailsID` = p0.`ID`
  LEFT JOIN `complaindetailsstatus` p1 ON c.`ComplainDetailsStatusID` = p1.`ID`
  LEFT JOIN `complain` p2 ON c.`ComplainID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserID` = p3.`ID`
 WHERE  (c.`ComplainDetailsID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ComplainDetailsStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`ComplainID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`UserID` IS NOT NULL AND p3.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complaindetailsassignment: orphan check OK - 0 rows across 4 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complaindetailsassignment` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '49b2f6ecaae711570578fe6cdf0ef82ace8223ecaa70f03428a93c8d42087b5a', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaindetailsassignment/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complaindetailsassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaindetailsassignment`
  ADD CONSTRAINT `complaindetailsassignment_ComplainDetailsID` FOREIGN KEY (`ComplainDetailsID`) REFERENCES `complaindetails` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetailsassignment_ComplainDetailsStatusID` FOREIGN KEY (`ComplainDetailsStatusID`) REFERENCES `complaindetailsstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetailsassignment_ComplainID` FOREIGN KEY (`ComplainID`) REFERENCES `complain` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaindetailsassignment_UserID` FOREIGN KEY (`UserID`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '001fdc8957538190d1115b8ea58583dda3af9d1596ff6862e68c917530b4d2f7', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: complainitem    (transaction)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complainitem/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complainitem/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainitem`
  MODIFY COLUMN `ComplainStatusID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `ComplainTypeID` int DEFAULT NULL,
  MODIFY COLUMN `PrincipalID` int DEFAULT NULL,
  ADD INDEX `complainitem_ComplainStatusID` (`ComplainStatusID`),
  ADD INDEX `complainitem_ComplainTypeID` (`ComplainTypeID`),
  ADD INDEX `complainitem_PrincipalID` (`PrincipalID`),
  ADD INDEX `complainitem_UserIDInput` (`UserIDInput`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '840bf2f53a1c0f86d0c3dfdc9fbbcdd0c7ed1dfebb7707c6a4893caaf6292723', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainitem/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complainitem/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complainitem` c
  LEFT JOIN `complainitemstatus` p0 ON c.`ComplainStatusID` = p0.`ID`
  LEFT JOIN `complainitemtype` p1 ON c.`ComplainTypeID` = p1.`ID`
  LEFT JOIN `principal` p2 ON c.`PrincipalID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserIDInput` = p3.`ID`
   SET
       c.`ComplainStatusID` = IF((c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ComplainStatusID`),
       c.`ComplainTypeID` = IF((c.`ComplainTypeID` IS NOT NULL AND (c.`ComplainTypeID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ComplainTypeID`),
       c.`PrincipalID` = IF((c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p2.`ID` IS NULL)), NULL, c.`PrincipalID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p3.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ComplainTypeID` IS NOT NULL AND (c.`ComplainTypeID` = 0 OR p1.`ID` IS NULL))
    OR (c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p2.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p3.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '915863db11343dfe0e15bf8dd14aa104ff9f5f050882f6bcff2fd5f54b36c95a', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complainitem/30_assert  --  source section 7b
-- Orphan assertion over this table's 4 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complainitem/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complainitem` c
  LEFT JOIN `complainitemstatus` p0 ON c.`ComplainStatusID` = p0.`ID`
  LEFT JOIN `complainitemtype` p1 ON c.`ComplainTypeID` = p1.`ID`
  LEFT JOIN `principal` p2 ON c.`PrincipalID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserIDInput` = p3.`ID`
 WHERE  (c.`ComplainStatusID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ComplainTypeID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`PrincipalID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p3.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complainitem: orphan check OK - 0 rows across 4 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complainitem` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '83017f74a6cc83bdad5aab42cc5b815bb6df6ba032a01d68ced40aa57469b477', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainitem/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complainitem/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainitem`
  ADD CONSTRAINT `complainitem_ComplainStatusID` FOREIGN KEY (`ComplainStatusID`) REFERENCES `complainitemstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitem_ComplainTypeID` FOREIGN KEY (`ComplainTypeID`) REFERENCES `complainitemtype` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitem_PrincipalID` FOREIGN KEY (`PrincipalID`) REFERENCES `principal` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitem_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '6c58801320b6cdc1df13c46b31686f97cf3d2a8bc4fc295c6da2161c0f8e957f', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: complainitemassignment    (detail, owned by complainitem)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complainitemassignment/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complainitemassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainitemassignment`
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `ComplainItemID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainItemStatusID` int DEFAULT NULL,
  MODIFY COLUMN `DepartmentID` int DEFAULT NULL,
  ADD INDEX `complainitemassignment_ComplainItemID` (`ComplainItemID`),
  ADD INDEX `complainitemassignment_ComplainItemStatusID` (`ComplainItemStatusID`),
  ADD INDEX `complainitemassignment_DepartmentID` (`DepartmentID`),
  ADD INDEX `complainitemassignment_UserIDInput` (`UserIDInput`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'ffbeb3a2a5902415c40c77d184e143ab47453c905cb9852010513be78a33499c', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainitemassignment/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complainitemassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complainitemassignment` c
  LEFT JOIN `complainitem` p0 ON c.`ComplainItemID` = p0.`ID`
  LEFT JOIN `complainitemstatus` p1 ON c.`ComplainItemStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
   SET
       c.`ComplainItemID` = IF((c.`ComplainItemID` IS NOT NULL AND (c.`ComplainItemID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ComplainItemID`),
       c.`ComplainItemStatusID` = IF((c.`ComplainItemStatusID` IS NOT NULL AND (c.`ComplainItemStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ComplainItemStatusID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`ComplainItemID` IS NOT NULL AND (c.`ComplainItemID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ComplainItemStatusID` IS NOT NULL AND (c.`ComplainItemStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '0682313f9440046d4472c536b5b5a53bb0118b02b5f9ee491389e0dea2a76fd2', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complainitemassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 3 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complainitemassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complainitemassignment` c
  LEFT JOIN `complainitem` p0 ON c.`ComplainItemID` = p0.`ID`
  LEFT JOIN `complainitemstatus` p1 ON c.`ComplainItemStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
 WHERE  (c.`ComplainItemID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ComplainItemStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p2.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complainitemassignment: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complainitemassignment` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '9624adbd3a49dacf49852caa03bbd8829387de017353695089f2575255a3e7dd', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainitemassignment/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complainitemassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainitemassignment`
  ADD CONSTRAINT `complainitemassignment_ComplainItemID` FOREIGN KEY (`ComplainItemID`) REFERENCES `complainitem` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemassignment_ComplainItemStatusID` FOREIGN KEY (`ComplainItemStatusID`) REFERENCES `complainitemstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemassignment_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '4e4c95afe9380c6fe1080df39f9351ae39e839f954470ca87f9aeffd08930e76', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: complainitemdetails    (detail, owned by complainitem)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complainitemdetails/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complainitemdetails/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainitemdetails`
  MODIFY COLUMN `ComplainItemID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainDetailStatusID` int DEFAULT NULL,
  MODIFY COLUMN `BarangID` int DEFAULT NULL,
  MODIFY COLUMN `PackingMonth` int DEFAULT NULL,
  MODIFY COLUMN `PackingYear` int DEFAULT NULL,
  MODIFY COLUMN `CompanyID` int DEFAULT NULL,
  MODIFY COLUMN `DivisionID` int DEFAULT NULL,
  MODIFY COLUMN `IndustryID` int DEFAULT NULL,
  MODIFY COLUMN `ApplicationID` int DEFAULT NULL,
  ADD INDEX `complainitemdetails_ApplicationID` (`ApplicationID`),
  ADD INDEX `complainitemdetails_BarangID` (`BarangID`),
  ADD INDEX `complainitemdetails_CompanyID` (`CompanyID`),
  ADD INDEX `complainitemdetails_ComplainDetailStatusID` (`ComplainDetailStatusID`),
  ADD INDEX `complainitemdetails_ComplainItemID` (`ComplainItemID`),
  ADD INDEX `complainitemdetails_DivisionID` (`DivisionID`),
  ADD INDEX `complainitemdetails_IndustryID` (`IndustryID`),
  ADD INDEX `complainitemdetails_PackingMonth` (`PackingMonth`),
  ADD INDEX `complainitemdetails_PackingYear` (`PackingYear`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '2933f23d1b834334a8a750db3ba869dbb6ca00e14421f24d5ac433c5e515cfd5', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainitemdetails/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complainitemdetails/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complainitemdetails` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`BarangID` = p1.`ID`
  LEFT JOIN `company` p2 ON c.`CompanyID` = p2.`ID`
  LEFT JOIN `complaindetailsstatus` p3 ON c.`ComplainDetailStatusID` = p3.`ID`
  LEFT JOIN `complainitem` p4 ON c.`ComplainItemID` = p4.`ID`
  LEFT JOIN `division` p5 ON c.`DivisionID` = p5.`ID`
  LEFT JOIN `industry` p6 ON c.`IndustryID` = p6.`ID`
  LEFT JOIN `packing` p7 ON c.`PackingMonth` = p7.`ID`
  LEFT JOIN `packing` p8 ON c.`PackingYear` = p8.`ID`
   SET
       c.`ApplicationID` = IF((c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ApplicationID`),
       c.`BarangID` = IF((c.`BarangID` IS NOT NULL AND (c.`BarangID` = 0 OR p1.`ID` IS NULL)), NULL, c.`BarangID`),
       c.`CompanyID` = IF((c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p2.`ID` IS NULL)), NULL, c.`CompanyID`),
       c.`ComplainDetailStatusID` = IF((c.`ComplainDetailStatusID` IS NOT NULL AND (c.`ComplainDetailStatusID` = 0 OR p3.`ID` IS NULL)), NULL, c.`ComplainDetailStatusID`),
       c.`ComplainItemID` = IF((c.`ComplainItemID` IS NOT NULL AND (c.`ComplainItemID` = 0 OR p4.`ID` IS NULL)), NULL, c.`ComplainItemID`),
       c.`DivisionID` = IF((c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p5.`ID` IS NULL)), NULL, c.`DivisionID`),
       c.`IndustryID` = IF((c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p6.`ID` IS NULL)), NULL, c.`IndustryID`),
       c.`PackingMonth` = IF((c.`PackingMonth` IS NOT NULL AND (c.`PackingMonth` = 0 OR p7.`ID` IS NULL)), NULL, c.`PackingMonth`),
       c.`PackingYear` = IF((c.`PackingYear` IS NOT NULL AND (c.`PackingYear` = 0 OR p8.`ID` IS NULL)), NULL, c.`PackingYear`)
 WHERE  (c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL))
    OR (c.`BarangID` IS NOT NULL AND (c.`BarangID` = 0 OR p1.`ID` IS NULL))
    OR (c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p2.`ID` IS NULL))
    OR (c.`ComplainDetailStatusID` IS NOT NULL AND (c.`ComplainDetailStatusID` = 0 OR p3.`ID` IS NULL))
    OR (c.`ComplainItemID` IS NOT NULL AND (c.`ComplainItemID` = 0 OR p4.`ID` IS NULL))
    OR (c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p5.`ID` IS NULL))
    OR (c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p6.`ID` IS NULL))
    OR (c.`PackingMonth` IS NOT NULL AND (c.`PackingMonth` = 0 OR p7.`ID` IS NULL))
    OR (c.`PackingYear` IS NOT NULL AND (c.`PackingYear` = 0 OR p8.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'afee15b35d8559ce9e98f7d3fcf3bf5a2f155d1a2d952989b7322169e0b83513', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complainitemdetails/30_assert  --  source section 7b
-- Orphan assertion over this table's 9 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complainitemdetails/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complainitemdetails` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`BarangID` = p1.`ID`
  LEFT JOIN `company` p2 ON c.`CompanyID` = p2.`ID`
  LEFT JOIN `complaindetailsstatus` p3 ON c.`ComplainDetailStatusID` = p3.`ID`
  LEFT JOIN `complainitem` p4 ON c.`ComplainItemID` = p4.`ID`
  LEFT JOIN `division` p5 ON c.`DivisionID` = p5.`ID`
  LEFT JOIN `industry` p6 ON c.`IndustryID` = p6.`ID`
  LEFT JOIN `packing` p7 ON c.`PackingMonth` = p7.`ID`
  LEFT JOIN `packing` p8 ON c.`PackingYear` = p8.`ID`
 WHERE  (c.`ApplicationID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`BarangID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`CompanyID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`ComplainDetailStatusID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`ComplainItemID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`DivisionID` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`IndustryID` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`PackingMonth` IS NOT NULL AND p7.`ID` IS NULL)
    OR (c.`PackingYear` IS NOT NULL AND p8.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complainitemdetails: orphan check OK - 0 rows across 9 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complainitemdetails` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '6609dfb017eed483e282bb43b5ce33769a7a763e75c61ce02f49c1b5f61fbd6f', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainitemdetails/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complainitemdetails/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainitemdetails`
  ADD CONSTRAINT `complainitemdetails_ApplicationID` FOREIGN KEY (`ApplicationID`) REFERENCES `application` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetails_BarangID` FOREIGN KEY (`BarangID`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetails_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetails_ComplainDetailStatusID` FOREIGN KEY (`ComplainDetailStatusID`) REFERENCES `complaindetailsstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetails_ComplainItemID` FOREIGN KEY (`ComplainItemID`) REFERENCES `complainitem` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetails_DivisionID` FOREIGN KEY (`DivisionID`) REFERENCES `division` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetails_IndustryID` FOREIGN KEY (`IndustryID`) REFERENCES `industry` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetails_PackingMonth` FOREIGN KEY (`PackingMonth`) REFERENCES `packing` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetails_PackingYear` FOREIGN KEY (`PackingYear`) REFERENCES `packing` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '2f4a24f538ebd62287d90bda9db7bdc598e92d684138ac686d3a063b665560a6', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: complainitemdetailsaction    (detail, owned by complainitem)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complainitemdetailsaction/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complainitemdetailsaction/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainitemdetailsaction`
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `ComplainID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainStatusID` int DEFAULT NULL,
  MODIFY COLUMN `DepartmentID` int DEFAULT NULL,
  ADD INDEX `complainitemdetailsaction_ComplainID` (`ComplainID`),
  ADD INDEX `complainitemdetailsaction_ComplainStatusID` (`ComplainStatusID`),
  ADD INDEX `complainitemdetailsaction_DepartmentID` (`DepartmentID`),
  ADD INDEX `complainitemdetailsaction_UserIDInput` (`UserIDInput`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'edd774041a104f2791145a98b801de7607f3823ee9685f45264f0d16ae65f119', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainitemdetailsaction/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complainitemdetailsaction/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complainitemdetailsaction` c
  LEFT JOIN `complainitem` p0 ON c.`ComplainID` = p0.`ID`
  LEFT JOIN `complainitemstatus` p1 ON c.`ComplainStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
   SET
       c.`ComplainID` = IF((c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ComplainID`),
       c.`ComplainStatusID` = IF((c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ComplainStatusID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'e3b9c6c4e8c176c4fd5c82178d025c01f7a8e9375a388673dbff7af4e3955212', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complainitemdetailsaction/30_assert  --  source section 7b
-- Orphan assertion over this table's 3 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complainitemdetailsaction/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complainitemdetailsaction` c
  LEFT JOIN `complainitem` p0 ON c.`ComplainID` = p0.`ID`
  LEFT JOIN `complainitemstatus` p1 ON c.`ComplainStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
 WHERE  (c.`ComplainID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ComplainStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p2.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complainitemdetailsaction: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complainitemdetailsaction` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'fd1b4b4e0d761e977713f186c2ddc50a35f5da50b2842346481b0e218c046560', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainitemdetailsaction/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complainitemdetailsaction/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainitemdetailsaction`
  ADD CONSTRAINT `complainitemdetailsaction_ComplainID` FOREIGN KEY (`ComplainID`) REFERENCES `complainitem` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetailsaction_ComplainStatusID` FOREIGN KEY (`ComplainStatusID`) REFERENCES `complainitemstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetailsaction_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '9cf292eee87f71f1fcaaa7f48f0d963c40b315a993629337358f17b0c13f666d', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: complainitemdetailsactionassignment    (detail, owned by complainitem)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complainitemdetailsactionassignment/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complainitemdetailsactionassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainitemdetailsactionassignment`
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `ComplainItemID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainItemStatusID` int DEFAULT NULL,
  MODIFY COLUMN `DepartmentID` int DEFAULT NULL,
  ADD INDEX `complainitemdetailsactionassignment_ComplainItemID` (`ComplainItemID`),
  ADD INDEX `complainitemdetailsactionassignment_ComplainItemStatusID` (`ComplainItemStatusID`),
  ADD INDEX `complainitemdetailsactionassignment_DepartmentID` (`DepartmentID`),
  ADD INDEX `complainitemdetailsactionassignment_UserIDInput` (`UserIDInput`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '57d3483ccfb6f9a44b6e9ae5e75768f11a0a80bfb63789e0cc9a987b49e49da8', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainitemdetailsactionassignment/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complainitemdetailsactionassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complainitemdetailsactionassignment` c
  LEFT JOIN `complainitem` p0 ON c.`ComplainItemID` = p0.`ID`
  LEFT JOIN `complainitemstatus` p1 ON c.`ComplainItemStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
   SET
       c.`ComplainItemID` = IF((c.`ComplainItemID` IS NOT NULL AND (c.`ComplainItemID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ComplainItemID`),
       c.`ComplainItemStatusID` = IF((c.`ComplainItemStatusID` IS NOT NULL AND (c.`ComplainItemStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ComplainItemStatusID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`ComplainItemID` IS NOT NULL AND (c.`ComplainItemID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ComplainItemStatusID` IS NOT NULL AND (c.`ComplainItemStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'f1a14bd42cec07ec4029c2d1941aa944adbb05792c736a87f6f28aa2b371d1f4', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complainitemdetailsactionassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 3 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complainitemdetailsactionassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complainitemdetailsactionassignment` c
  LEFT JOIN `complainitem` p0 ON c.`ComplainItemID` = p0.`ID`
  LEFT JOIN `complainitemstatus` p1 ON c.`ComplainItemStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
 WHERE  (c.`ComplainItemID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ComplainItemStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p2.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complainitemdetailsactionassignment: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complainitemdetailsactionassignment` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '0e125f004a7fd41918c3ad8ee648ce90faf93fe2514d3f491353d801263c636e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainitemdetailsactionassignment/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complainitemdetailsactionassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainitemdetailsactionassignment`
  ADD CONSTRAINT `complainitemdetailsactionassignment_ComplainItemID` FOREIGN KEY (`ComplainItemID`) REFERENCES `complainitem` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetailsactionassignment_ComplainItemStatusID` FOREIGN KEY (`ComplainItemStatusID`) REFERENCES `complainitemstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetailsactionassignment_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'f985964d8f3aa14181382811d017780f9985890a5e218428c12242719d463295', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: complainitemdetailslot    (detail, owned by complainitem)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complainitemdetailslot/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complainitemdetailslot/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainitemdetailslot`
  MODIFY COLUMN `ComplainItemID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainItemDetailsID` int DEFAULT NULL,
  MODIFY COLUMN `PackagingID` int DEFAULT NULL,
  ADD INDEX `complainitemdetailslot_ComplainItemDetailsID` (`ComplainItemDetailsID`),
  ADD INDEX `complainitemdetailslot_ComplainItemID` (`ComplainItemID`),
  ADD INDEX `complainitemdetailslot_PackagingID` (`PackagingID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'cd1aca19ebab1cca4f1cb7bc55168e682ab87cc08c17b2e8bdf4a155c0596236', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainitemdetailslot/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complainitemdetailslot/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complainitemdetailslot` c
  LEFT JOIN `complainitemdetails` p0 ON c.`ComplainItemDetailsID` = p0.`ID`
  LEFT JOIN `complainitem` p1 ON c.`ComplainItemID` = p1.`ID`
  LEFT JOIN `packing` p2 ON c.`PackagingID` = p2.`ID`
   SET
       c.`ComplainItemDetailsID` = IF((c.`ComplainItemDetailsID` IS NOT NULL AND (c.`ComplainItemDetailsID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ComplainItemDetailsID`),
       c.`ComplainItemID` = IF((c.`ComplainItemID` IS NOT NULL AND (c.`ComplainItemID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ComplainItemID`),
       c.`PackagingID` = IF((c.`PackagingID` IS NOT NULL AND (c.`PackagingID` = 0 OR p2.`ID` IS NULL)), NULL, c.`PackagingID`)
 WHERE  (c.`ComplainItemDetailsID` IS NOT NULL AND (c.`ComplainItemDetailsID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ComplainItemID` IS NOT NULL AND (c.`ComplainItemID` = 0 OR p1.`ID` IS NULL))
    OR (c.`PackagingID` IS NOT NULL AND (c.`PackagingID` = 0 OR p2.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '425a9af853cc594e83cc63c51a899fc5eb47cd127f2342c62da40547c725202b', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complainitemdetailslot/30_assert  --  source section 7b
-- Orphan assertion over this table's 3 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complainitemdetailslot/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complainitemdetailslot` c
  LEFT JOIN `complainitemdetails` p0 ON c.`ComplainItemDetailsID` = p0.`ID`
  LEFT JOIN `complainitem` p1 ON c.`ComplainItemID` = p1.`ID`
  LEFT JOIN `packing` p2 ON c.`PackagingID` = p2.`ID`
 WHERE  (c.`ComplainItemDetailsID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ComplainItemID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`PackagingID` IS NOT NULL AND p2.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complainitemdetailslot: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complainitemdetailslot` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '5fba3fc71d1cc080251506bdda5239d76f354721ad88d629c54c3d2807073930', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainitemdetailslot/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complainitemdetailslot/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainitemdetailslot`
  ADD CONSTRAINT `complainitemdetailslot_ComplainItemDetailsID` FOREIGN KEY (`ComplainItemDetailsID`) REFERENCES `complainitemdetails` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetailslot_ComplainItemID` FOREIGN KEY (`ComplainItemID`) REFERENCES `complainitem` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetailslot_PackagingID` FOREIGN KEY (`PackagingID`) REFERENCES `packing` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '448741452fb14f76bf0d821c42780e6c0c4f01a395dfa428f70c99e099bf8cc2', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: complainitemdetailslotassignment    (detail, owned by complainitem)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complainitemdetailslotassignment/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complainitemdetailslotassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainitemdetailslotassignment`
  MODIFY COLUMN `ComplainItemID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainItemDetailsID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainItemDetailsLotID` int DEFAULT NULL,
  MODIFY COLUMN `DepID` int DEFAULT NULL,
  MODIFY COLUMN `PackagingID` int DEFAULT NULL,
  ADD INDEX `complainitemdetailslotassignment_ComplainItemDetailsID` (`ComplainItemDetailsID`),
  ADD INDEX `complainitemdetailslotassignment_ComplainItemDetailsLotID` (`ComplainItemDetailsLotID`),
  ADD INDEX `complainitemdetailslotassignment_ComplainItemID` (`ComplainItemID`),
  ADD INDEX `complainitemdetailslotassignment_DepartmentID` (`DepID`),
  ADD INDEX `complainitemdetailslotassignment_PackagingID` (`PackagingID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'c872d4740304323c1612965ecbe6b9bfc882bac49ff5b396b3d9735fde3673f7', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainitemdetailslotassignment/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complainitemdetailslotassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complainitemdetailslotassignment` c
  LEFT JOIN `complainitemdetails` p0 ON c.`ComplainItemDetailsID` = p0.`ID`
  LEFT JOIN `complainitemdetailslot` p1 ON c.`ComplainItemDetailsLotID` = p1.`ID`
  LEFT JOIN `complainitem` p2 ON c.`ComplainItemID` = p2.`ID`
  LEFT JOIN `packing` p3 ON c.`PackagingID` = p3.`ID`
   SET
       c.`ComplainItemDetailsID` = IF((c.`ComplainItemDetailsID` IS NOT NULL AND (c.`ComplainItemDetailsID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ComplainItemDetailsID`),
       c.`ComplainItemDetailsLotID` = IF((c.`ComplainItemDetailsLotID` IS NOT NULL AND (c.`ComplainItemDetailsLotID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ComplainItemDetailsLotID`),
       c.`ComplainItemID` = IF((c.`ComplainItemID` IS NOT NULL AND (c.`ComplainItemID` = 0 OR p2.`ID` IS NULL)), NULL, c.`ComplainItemID`),
       c.`PackagingID` = IF((c.`PackagingID` IS NOT NULL AND (c.`PackagingID` = 0 OR p3.`ID` IS NULL)), NULL, c.`PackagingID`)
 WHERE  (c.`ComplainItemDetailsID` IS NOT NULL AND (c.`ComplainItemDetailsID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ComplainItemDetailsLotID` IS NOT NULL AND (c.`ComplainItemDetailsLotID` = 0 OR p1.`ID` IS NULL))
    OR (c.`ComplainItemID` IS NOT NULL AND (c.`ComplainItemID` = 0 OR p2.`ID` IS NULL))
    OR (c.`PackagingID` IS NOT NULL AND (c.`PackagingID` = 0 OR p3.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '03742f4950c1193920e1b73304941ead95cb4e6e34b508f2e69b304e69102a05', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complainitemdetailslotassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 4 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complainitemdetailslotassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complainitemdetailslotassignment` c
  LEFT JOIN `complainitemdetails` p0 ON c.`ComplainItemDetailsID` = p0.`ID`
  LEFT JOIN `complainitemdetailslot` p1 ON c.`ComplainItemDetailsLotID` = p1.`ID`
  LEFT JOIN `complainitem` p2 ON c.`ComplainItemID` = p2.`ID`
  LEFT JOIN `packing` p3 ON c.`PackagingID` = p3.`ID`
 WHERE  (c.`ComplainItemDetailsID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ComplainItemDetailsLotID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`ComplainItemID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`PackagingID` IS NOT NULL AND p3.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complainitemdetailslotassignment: orphan check OK - 0 rows across 4 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complainitemdetailslotassignment` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'ed54d7a2440d7118729b4010b685d723b5c6b5503a235aae9d6cbc5e9bb5512e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complainitemdetailslotassignment/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complainitemdetailslotassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complainitemdetailslotassignment`
  ADD CONSTRAINT `complainitemdetailslotassignment_ComplainItemDetailsID` FOREIGN KEY (`ComplainItemDetailsID`) REFERENCES `complainitemdetails` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetailslotassignment_ComplainItemDetailsLotID` FOREIGN KEY (`ComplainItemDetailsLotID`) REFERENCES `complainitemdetailslot` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetailslotassignment_ComplainItemID` FOREIGN KEY (`ComplainItemID`) REFERENCES `complainitem` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complainitemdetailslotassignment_PackagingID` FOREIGN KEY (`PackagingID`) REFERENCES `packing` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'de71d1b745568bd2cb3003a27406e4031421534877950183f691d20a4185150c', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- --------------------------------------------------------------- postflight
-- DID THE WORK ACTUALLY LAND?
--
-- Every step records itself in `_migration_ledger` immediately after its statement runs,
-- WITHOUT checking that the statement succeeded. That is inherited from step/ unchanged,
-- and there it is safe because run.sh runs mysql without --force, so the first error stops
-- everything. Imported by hand, the client decides -- and "continue on error" would leave
-- failed steps marked applied.
--
-- So this file checks its own work against information_schema before it finishes. It is
-- the only thing here that is NOT copied from step/. It reads; it changes nothing.

-- postflight-set: fk
SET @want_fk = 61;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_fk, @miss_fk
  FROM (SELECT 'complain.complain_CompanyCPID' AS n UNION ALL SELECT 'complain.complain_CompanyID' UNION ALL SELECT 'complain.complain_ComplainReasonID' UNION ALL SELECT 'complain.complain_ComplainStatusID' UNION ALL SELECT 'complain.complain_ComplainTypeID' UNION ALL SELECT 'complain.complain_DivisionID' UNION ALL SELECT 'complain.complain_UserIDInput' UNION ALL SELECT 'complain.complain_UserIDSales' UNION ALL SELECT 'complainassignment.complainassignment_ComplainID' UNION ALL SELECT 'complainassignment.complainassignment_ComplainStatusID' UNION ALL SELECT 'complainassignment.complainassignment_UserID' UNION ALL SELECT 'complaindetails.complaindetails_ApplicationID' UNION ALL SELECT 'complaindetails.complaindetails_BarangID' UNION ALL SELECT 'complaindetails.complaindetails_ComplainDetailsStatusID' UNION ALL SELECT 'complaindetails.complaindetails_ComplainID' UNION ALL SELECT 'complaindetails.complaindetails_PrincipalID' UNION ALL SELECT 'complaindetails.complaindetails_SatuanComplainQuantityID' UNION ALL SELECT 'complaindetails.complaindetails_SatuanPackingID' UNION ALL SELECT 'complaindetails.complaindetails_SatuanUnitPriceUSD' UNION ALL SELECT 'complaindetailsaction.complaindetailsaction_ComplainDetailsID' UNION ALL SELECT 'complaindetailsaction.complaindetailsaction_ComplainDetailsStatusID' UNION ALL SELECT 'complaindetailsaction.complaindetailsaction_ComplainID' UNION ALL SELECT 'complaindetailsaction.complaindetailsaction_UserID' UNION ALL SELECT 'complaindetailsactionassignment.complaindetailsactionassignment_ComplainDetailsActionID' UNION ALL SELECT 'complaindetailsactionassignment.complaindetailsactionassignment_ComplainDetailsID' UNION ALL SELECT 'complaindetailsactionassignment.complaindetailsactionassignment_ComplainDetailsStatusID' UNION ALL SELECT 'complaindetailsactionassignment.complaindetailsactionassignment_ComplainID' UNION ALL SELECT 'complaindetailsactionassignment.complaindetailsactionassignment_UserID' UNION ALL SELECT 'complaindetailsassignment.complaindetailsassignment_ComplainDetailsID' UNION ALL SELECT 'complaindetailsassignment.complaindetailsassignment_ComplainDetailsStatusID' UNION ALL SELECT 'complaindetailsassignment.complaindetailsassignment_ComplainID' UNION ALL SELECT 'complaindetailsassignment.complaindetailsassignment_UserID' UNION ALL SELECT 'complainitem.complainitem_ComplainStatusID' UNION ALL SELECT 'complainitem.complainitem_ComplainTypeID' UNION ALL SELECT 'complainitem.complainitem_PrincipalID' UNION ALL SELECT 'complainitem.complainitem_UserIDInput' UNION ALL SELECT 'complainitemassignment.complainitemassignment_ComplainItemID' UNION ALL SELECT 'complainitemassignment.complainitemassignment_ComplainItemStatusID' UNION ALL SELECT 'complainitemassignment.complainitemassignment_UserIDInput' UNION ALL SELECT 'complainitemdetails.complainitemdetails_ApplicationID' UNION ALL SELECT 'complainitemdetails.complainitemdetails_BarangID' UNION ALL SELECT 'complainitemdetails.complainitemdetails_CompanyID' UNION ALL SELECT 'complainitemdetails.complainitemdetails_ComplainDetailStatusID' UNION ALL SELECT 'complainitemdetails.complainitemdetails_ComplainItemID' UNION ALL SELECT 'complainitemdetails.complainitemdetails_DivisionID' UNION ALL SELECT 'complainitemdetails.complainitemdetails_IndustryID' UNION ALL SELECT 'complainitemdetails.complainitemdetails_PackingMonth' UNION ALL SELECT 'complainitemdetails.complainitemdetails_PackingYear' UNION ALL SELECT 'complainitemdetailsaction.complainitemdetailsaction_ComplainID' UNION ALL SELECT 'complainitemdetailsaction.complainitemdetailsaction_ComplainStatusID' UNION ALL SELECT 'complainitemdetailsaction.complainitemdetailsaction_UserIDInput' UNION ALL SELECT 'complainitemdetailsactionassignment.complainitemdetailsactionassignment_ComplainItemID' UNION ALL SELECT 'complainitemdetailsactionassignment.complainitemdetailsactionassignment_ComplainItemStatusID' UNION ALL SELECT 'complainitemdetailsactionassignment.complainitemdetailsactionassignment_UserIDInput' UNION ALL SELECT 'complainitemdetailslot.complainitemdetailslot_ComplainItemDetailsID' UNION ALL SELECT 'complainitemdetailslot.complainitemdetailslot_ComplainItemID' UNION ALL SELECT 'complainitemdetailslot.complainitemdetailslot_PackagingID' UNION ALL SELECT 'complainitemdetailslotassignment.complainitemdetailslotassignment_ComplainItemDetailsID' UNION ALL SELECT 'complainitemdetailslotassignment.complainitemdetailslotassignment_ComplainItemDetailsLotID' UNION ALL SELECT 'complainitemdetailslotassignment.complainitemdetailslotassignment_ComplainItemID' UNION ALL SELECT 'complainitemdetailslotassignment.complainitemdetailslotassignment_PackagingID') _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', CONSTRAINT_NAME) FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE() AND CONSTRAINT_TYPE = 'FOREIGN KEY');
SET @have_fk = @want_fk - @missn_fk;
SET @pf_fk = IF(@missn_fk = 0,
    CONCAT('SELECT ''postflight foreign keys: ', @have_fk, '/', @want_fk, ' present'' AS postflight_fk'),
    CONCAT('SELECT `ABORT postflight: MISSING foreign keys: ', @miss_fk,
           ' -- ', @missn_fk, ' of ', @want_fk, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_fk; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- postflight-set: idx
SET @want_idx = 68;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_idx, @miss_idx
  FROM (SELECT 'complain.ComplainStatusID' AS n UNION ALL SELECT 'complain.complain_CompanyCPID' UNION ALL SELECT 'complain.complain_CompanyID' UNION ALL SELECT 'complain.complain_ComplainReasonID' UNION ALL SELECT 'complain.complain_ComplainTypeID' UNION ALL SELECT 'complain.complain_DivisionID' UNION ALL SELECT 'complain.complain_UserIDInput' UNION ALL SELECT 'complain.complain_UserIDSales' UNION ALL SELECT 'complainassignment.ComplainID' UNION ALL SELECT 'complainassignment.complainassignment_ComplainStatusID' UNION ALL SELECT 'complainassignment.complainassignment_UserID' UNION ALL SELECT 'complaindetails.ComplainID' UNION ALL SELECT 'complaindetails.complaindetails_ApplicationID' UNION ALL SELECT 'complaindetails.complaindetails_BarangID' UNION ALL SELECT 'complaindetails.complaindetails_ComplainDetailsStatusID' UNION ALL SELECT 'complaindetails.complaindetails_PrincipalID' UNION ALL SELECT 'complaindetails.complaindetails_SatuanComplainQuantityID' UNION ALL SELECT 'complaindetails.complaindetails_SatuanPackingID' UNION ALL SELECT 'complaindetails.complaindetails_SatuanUnitPriceUSD' UNION ALL SELECT 'complaindetailsaction.ComplainID' UNION ALL SELECT 'complaindetailsaction.complaindetailsaction_ComplainDetailsID' UNION ALL SELECT 'complaindetailsaction.complaindetailsaction_ComplainDetailsStatusID' UNION ALL SELECT 'complaindetailsaction.complaindetailsaction_DepartmentID' UNION ALL SELECT 'complaindetailsaction.complaindetailsaction_UserID' UNION ALL SELECT 'complaindetailsactionassignment.ComplainDetailsActionID' UNION ALL SELECT 'complaindetailsactionassignment.complaindetailsactionassignment_ComplainDetailsID' UNION ALL SELECT 'complaindetailsactionassignment.complaindetailsactionassignment_ComplainDetailsStatusID' UNION ALL SELECT 'complaindetailsactionassignment.complaindetailsactionassignment_ComplainID' UNION ALL SELECT 'complaindetailsactionassignment.complaindetailsactionassignment_DepartmentID' UNION ALL SELECT 'complaindetailsactionassignment.complaindetailsactionassignment_UserID' UNION ALL SELECT 'complaindetailsassignment.ComplainID' UNION ALL SELECT 'complaindetailsassignment.complaindetailsassignment_ComplainDetailsID' UNION ALL SELECT 'complaindetailsassignment.complaindetailsassignment_ComplainDetailsStatusID' UNION ALL SELECT 'complaindetailsassignment.complaindetailsassignment_DepartmentID' UNION ALL SELECT 'complaindetailsassignment.complaindetailsassignment_UserID' UNION ALL SELECT 'complainitem.complainitem_ComplainStatusID' UNION ALL SELECT 'complainitem.complainitem_ComplainTypeID' UNION ALL SELECT 'complainitem.complainitem_PrincipalID' UNION ALL SELECT 'complainitem.complainitem_UserIDInput' UNION ALL SELECT 'complainitemassignment.complainitemassignment_ComplainItemID' UNION ALL SELECT 'complainitemassignment.complainitemassignment_ComplainItemStatusID' UNION ALL SELECT 'complainitemassignment.complainitemassignment_DepartmentID' UNION ALL SELECT 'complainitemassignment.complainitemassignment_UserIDInput' UNION ALL SELECT 'complainitemdetails.complainitemdetails_ApplicationID' UNION ALL SELECT 'complainitemdetails.complainitemdetails_BarangID' UNION ALL SELECT 'complainitemdetails.complainitemdetails_CompanyID' UNION ALL SELECT 'complainitemdetails.complainitemdetails_ComplainDetailStatusID' UNION ALL SELECT 'complainitemdetails.complainitemdetails_ComplainItemID' UNION ALL SELECT 'complainitemdetails.complainitemdetails_DivisionID' UNION ALL SELECT 'complainitemdetails.complainitemdetails_IndustryID' UNION ALL SELECT 'complainitemdetails.complainitemdetails_PackingMonth' UNION ALL SELECT 'complainitemdetails.complainitemdetails_PackingYear' UNION ALL SELECT 'complainitemdetailsaction.complainitemdetailsaction_ComplainID' UNION ALL SELECT 'complainitemdetailsaction.complainitemdetailsaction_ComplainStatusID' UNION ALL SELECT 'complainitemdetailsaction.complainitemdetailsaction_DepartmentID' UNION ALL SELECT 'complainitemdetailsaction.complainitemdetailsaction_UserIDInput' UNION ALL SELECT 'complainitemdetailsactionassignment.complainitemdetailsactionassignment_ComplainItemID' UNION ALL SELECT 'complainitemdetailsactionassignment.complainitemdetailsactionassignment_ComplainItemStatusID' UNION ALL SELECT 'complainitemdetailsactionassignment.complainitemdetailsactionassignment_DepartmentID' UNION ALL SELECT 'complainitemdetailsactionassignment.complainitemdetailsactionassignment_UserIDInput' UNION ALL SELECT 'complainitemdetailslot.complainitemdetailslot_ComplainItemDetailsID' UNION ALL SELECT 'complainitemdetailslot.complainitemdetailslot_ComplainItemID' UNION ALL SELECT 'complainitemdetailslot.complainitemdetailslot_PackagingID' UNION ALL SELECT 'complainitemdetailslotassignment.complainitemdetailslotassignment_ComplainItemDetailsID' UNION ALL SELECT 'complainitemdetailslotassignment.complainitemdetailslotassignment_ComplainItemDetailsLotID' UNION ALL SELECT 'complainitemdetailslotassignment.complainitemdetailslotassignment_ComplainItemID' UNION ALL SELECT 'complainitemdetailslotassignment.complainitemdetailslotassignment_DepartmentID' UNION ALL SELECT 'complainitemdetailslotassignment.complainitemdetailslotassignment_PackagingID') _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', INDEX_NAME) FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE());
SET @have_idx = @want_idx - @missn_idx;
SET @pf_idx = IF(@missn_idx = 0,
    CONCAT('SELECT ''postflight indexes: ', @have_idx, '/', @want_idx, ' present'' AS postflight_idx'),
    CONCAT('SELECT `ABORT postflight: MISSING indexes: ', @miss_idx,
           ' -- ', @missn_idx, ' of ', @want_idx, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_idx; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- postflight-set: typ
SET @want_typ = 71;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_typ, @miss_typ
  FROM (SELECT 'complain.CompanyCPID.int' AS n UNION ALL SELECT 'complain.CompanyID.int' UNION ALL SELECT 'complain.ComplainReasonID.int' UNION ALL SELECT 'complain.ComplainStatusID.int' UNION ALL SELECT 'complain.ComplainTypeID.int' UNION ALL SELECT 'complain.DivisionID.int' UNION ALL SELECT 'complain.UserIDInput.int' UNION ALL SELECT 'complain.UserIDSales.int' UNION ALL SELECT 'complainassignment.Comment.text' UNION ALL SELECT 'complainassignment.ComplainID.int' UNION ALL SELECT 'complainassignment.ComplainStatusID.int' UNION ALL SELECT 'complainassignment.UserID.int' UNION ALL SELECT 'complaindetails.ApplicationID.int' UNION ALL SELECT 'complaindetails.BarangID.int' UNION ALL SELECT 'complaindetails.ComplainDetailsStatusID.int' UNION ALL SELECT 'complaindetails.ComplainID.int' UNION ALL SELECT 'complaindetails.ComplainQuantity.decimal' UNION ALL SELECT 'complaindetails.PrincipalID.int' UNION ALL SELECT 'complaindetails.QuantityPacking.decimal' UNION ALL SELECT 'complaindetails.SatuanComplainQuantityID.int' UNION ALL SELECT 'complaindetails.SatuanPackingID.int' UNION ALL SELECT 'complaindetails.SatuanUnitPriceUSD.int' UNION ALL SELECT 'complaindetailsaction.ComplainDetailsID.int' UNION ALL SELECT 'complaindetailsaction.ComplainDetailsStatusID.int' UNION ALL SELECT 'complaindetailsaction.ComplainID.int' UNION ALL SELECT 'complaindetailsaction.DepartmentID.int' UNION ALL SELECT 'complaindetailsaction.UserID.int' UNION ALL SELECT 'complaindetailsactionassignment.ComplainDetailsActionID.int' UNION ALL SELECT 'complaindetailsactionassignment.ComplainDetailsID.int' UNION ALL SELECT 'complaindetailsactionassignment.ComplainDetailsStatusID.int' UNION ALL SELECT 'complaindetailsactionassignment.ComplainID.int' UNION ALL SELECT 'complaindetailsactionassignment.DepartmentID.int' UNION ALL SELECT 'complaindetailsactionassignment.UserID.int' UNION ALL SELECT 'complaindetailsassignment.ComplainDetailsID.int' UNION ALL SELECT 'complaindetailsassignment.ComplainDetailsStatusID.int' UNION ALL SELECT 'complaindetailsassignment.ComplainID.int' UNION ALL SELECT 'complaindetailsassignment.DepartmentID.int' UNION ALL SELECT 'complaindetailsassignment.UserID.int' UNION ALL SELECT 'complainitem.ComplainStatusID.int' UNION ALL SELECT 'complainitem.ComplainTypeID.int' UNION ALL SELECT 'complainitem.PrincipalID.int' UNION ALL SELECT 'complainitem.UserIDInput.int' UNION ALL SELECT 'complainitemassignment.ComplainItemID.int' UNION ALL SELECT 'complainitemassignment.ComplainItemStatusID.int' UNION ALL SELECT 'complainitemassignment.DepartmentID.int' UNION ALL SELECT 'complainitemassignment.UserIDInput.int' UNION ALL SELECT 'complainitemdetails.ApplicationID.int' UNION ALL SELECT 'complainitemdetails.BarangID.int' UNION ALL SELECT 'complainitemdetails.CompanyID.int' UNION ALL SELECT 'complainitemdetails.ComplainDetailStatusID.int' UNION ALL SELECT 'complainitemdetails.ComplainItemID.int' UNION ALL SELECT 'complainitemdetails.DivisionID.int' UNION ALL SELECT 'complainitemdetails.IndustryID.int' UNION ALL SELECT 'complainitemdetails.PackingMonth.int' UNION ALL SELECT 'complainitemdetails.PackingYear.int' UNION ALL SELECT 'complainitemdetailsaction.ComplainID.int' UNION ALL SELECT 'complainitemdetailsaction.ComplainStatusID.int' UNION ALL SELECT 'complainitemdetailsaction.DepartmentID.int' UNION ALL SELECT 'complainitemdetailsaction.UserIDInput.int' UNION ALL SELECT 'complainitemdetailsactionassignment.ComplainItemID.int' UNION ALL SELECT 'complainitemdetailsactionassignment.ComplainItemStatusID.int' UNION ALL SELECT 'complainitemdetailsactionassignment.DepartmentID.int' UNION ALL SELECT 'complainitemdetailsactionassignment.UserIDInput.int' UNION ALL SELECT 'complainitemdetailslot.ComplainItemDetailsID.int' UNION ALL SELECT 'complainitemdetailslot.ComplainItemID.int' UNION ALL SELECT 'complainitemdetailslot.PackagingID.int' UNION ALL SELECT 'complainitemdetailslotassignment.ComplainItemDetailsID.int' UNION ALL SELECT 'complainitemdetailslotassignment.ComplainItemDetailsLotID.int' UNION ALL SELECT 'complainitemdetailslotassignment.ComplainItemID.int' UNION ALL SELECT 'complainitemdetailslotassignment.DepID.int' UNION ALL SELECT 'complainitemdetailslotassignment.PackagingID.int') _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', COLUMN_NAME, '.', DATA_TYPE) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE());
SET @have_typ = @want_typ - @missn_typ;
SET @pf_typ = IF(@missn_typ = 0,
    CONCAT('SELECT ''postflight retyped columns: ', @have_typ, '/', @want_typ, ' present'' AS postflight_typ'),
    CONCAT('SELECT `ABORT postflight: MISSING retyped columns: ', @miss_typ,
           ' -- ', @missn_typ, ' of ', @want_typ, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_typ; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- --------------------------------------------------------------- restore
-- IFNULL on all four: if phpMyAdmin resumed this import on a fresh connection the
-- @OLD_ variables are gone, and a bare SET from NULL is ERROR 1231.
--
-- The CAST is on the two timeouts and NOWHERE ELSE, on purpose. An INTEGER system
-- variable rejects IFNULL()'s result type outright (ERROR 1232, every time, not only
-- when NULL). FOREIGN_KEY_CHECKS is a boolean and SQL_MODE is a set; both accept a
-- string result, so they need no CAST. Do not "fix" the asymmetry, and do not copy
-- line 3's shape onto a new integer variable.
SET SESSION lock_wait_timeout = CAST(IFNULL(@OLD_LOCK_WAIT, 86400) AS UNSIGNED);
SET SESSION innodb_lock_wait_timeout = CAST(IFNULL(@OLD_INNODB_LOCK_WAIT, 50) AS UNSIGNED);
