-- Many-to-many: designations ↔ departments
-- Preserve existing links; do not delete duplicate designation rows.

CREATE TABLE `designation_departments` (
    `designationId` VARCHAR(191) NOT NULL,
    `departmentId` VARCHAR(191) NOT NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),

    PRIMARY KEY (`designationId`, `departmentId`),
    INDEX `designation_departments_departmentId_idx`(`departmentId`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- Backfill from the previous 1:1 departmentId column
INSERT INTO `designation_departments` (`designationId`, `departmentId`, `createdAt`)
SELECT `id`, `departmentId`, `createdAt` FROM `designations`
WHERE `departmentId` IS NOT NULL;

-- Drop old unique + FK + column
ALTER TABLE `designations` DROP INDEX `designations_title_departmentId_key`;
ALTER TABLE `designations` DROP FOREIGN KEY `designations_departmentId_fkey`;
ALTER TABLE `designations` DROP COLUMN `departmentId`;

ALTER TABLE `designation_departments`
  ADD CONSTRAINT `designation_departments_designationId_fkey`
  FOREIGN KEY (`designationId`) REFERENCES `designations`(`id`)
  ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE `designation_departments`
  ADD CONSTRAINT `designation_departments_departmentId_fkey`
  FOREIGN KEY (`departmentId`) REFERENCES `departments`(`id`)
  ON DELETE CASCADE ON UPDATE CASCADE;

CREATE INDEX `designations_title_idx` ON `designations`(`title`);
