-- Cache the cross-system organization/department mapping used to resolve FindS org snapshots
-- (collected passively from personnel_match, since FindS exposes no bulk org-list API) to the
-- local platform's corp_info/department tree.
CREATE TABLE IF NOT EXISTS `org_match` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'primary key',
  `source_system` varchar(32) NOT NULL DEFAULT 'FINDS' COMMENT 'external source system',
  `source_config_code` varchar(64) NOT NULL DEFAULT 'FINDS' COMMENT 'FindS config scope',
  `finds_corpinfo_id` varchar(64) DEFAULT NULL COMMENT 'FindS company id snapshot (rarely populated)',
  `finds_corpinfo_name` varchar(255) NOT NULL DEFAULT '' COMMENT 'FindS company/org name snapshot (top level)',
  `finds_department_name` varchar(255) NOT NULL DEFAULT '' COMMENT 'FindS department name snapshot, empty when absent',
  `local_corpinfo_id` varchar(64) DEFAULT NULL COMMENT 'matched local corp_info.corpinfo_id (root company)',
  `local_corpinfo_name` varchar(255) DEFAULT NULL COMMENT 'matched local corp_info.corp_name snapshot',
  `local_department_id` bigint DEFAULT NULL COMMENT 'matched local department.id (specific dept/sub-company node)',
  `local_department_name` varchar(255) DEFAULT NULL COMMENT 'matched local department.dept_name snapshot',
  `match_status` varchar(32) NOT NULL DEFAULT 'UNMATCHED' COMMENT 'MATCHED/UNMATCHED/AMBIGUOUS/DISABLED',
  `match_type` varchar(32) DEFAULT NULL COMMENT 'CORP_NAME/DEPARTMENT_NAME',
  `last_seen_time` datetime DEFAULT NULL COMMENT 'last time observed from FindS (via personnel_match)',
  `last_sync_time` datetime DEFAULT NULL COMMENT 'last mapping synchronization time',
  `sync_status` varchar(32) NOT NULL DEFAULT 'SUCCESS' COMMENT 'SUCCESS/FAIL',
  `sync_error` varchar(1000) DEFAULT NULL COMMENT 'last synchronization error',
  `delete_enum` varchar(32) NOT NULL DEFAULT 'FALSE' COMMENT 'soft delete flag',
  `remarks` varchar(500) DEFAULT NULL COMMENT 'remarks',
  `tenant_id` bigint DEFAULT NULL COMMENT 'tenant id',
  `org_id` bigint DEFAULT NULL COMMENT 'organization id',
  `env` varchar(32) DEFAULT NULL COMMENT 'environment',
  `version` int NOT NULL DEFAULT 0 COMMENT 'version',
  `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'created time',
  `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'updated time',
  `create_id` bigint DEFAULT NULL COMMENT 'creator id',
  `update_id` bigint DEFAULT NULL COMMENT 'updater id',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_org_match_source_name_delete` (`source_config_code`, `finds_corpinfo_name`, `finds_department_name`, `delete_enum`),
  KEY `idx_org_match_local_corpinfo` (`local_corpinfo_id`, `match_status`),
  KEY `idx_org_match_local_department` (`local_department_id`),
  KEY `idx_org_match_last_seen` (`last_seen_time`),
  KEY `idx_org_match_tenant_org` (`tenant_id`, `org_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='FindS to local organization/department mapping';
