START TRANSACTION;

ALTER TABLE maintenance_ftth_tickets
  MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT;

SET @zero_count := (
  SELECT COUNT(*)
  FROM maintenance_ftth_tickets
  WHERE id = 0
);

SET @next_id := (
  SELECT COALESCE(MAX(id), 0) + 1
  FROM maintenance_ftth_tickets
  WHERE id <> 0
);

UPDATE maintenance_ftth_tickets
SET id = @next_id
WHERE id = 0
  AND @zero_count = 1
LIMIT 1;

UPDATE maintenance_ftth_assignments
SET ticket_id = @next_id
WHERE ticket_id = 0
  AND @zero_count = 1;

UPDATE maintenance_ftth_reports
SET ticket_id = @next_id
WHERE ticket_id = 0
  AND @zero_count = 1;

UPDATE maintenance_ftth_ticket_events
SET ticket_id = @next_id
WHERE ticket_id = 0
  AND @zero_count = 1;

COMMIT;
