-- 請勿直接在 phpMyAdmin 手動執行；由 customer_import_api_ts.php 依環境映射安裝。
-- 喜樂燒臘｜共同顧客邏輯 Schema C3B-B1
-- 測試環境由程式自動映射為 *_ts；正式環境保留無後綴名稱。
-- 完整收銀大師原始資料＋BK 實際營運資料＋外部來源授權稽核＋雙來源比對＋收銀大師匯出預留
-- 只建立 *_ts 測試表，不接觸正式 customers / orders。

SET NAMES utf8mb4;

CREATE TABLE IF NOT EXISTS customer_import_batches (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  batch_code VARCHAR(64) NOT NULL,
  source_system VARCHAR(40) NOT NULL DEFAULT 'cashier_master',
  source_filename VARCHAR(255) NOT NULL DEFAULT '',
  source_encoding VARCHAR(40) NOT NULL DEFAULT '',
  source_size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
  expected_header_count INT UNSIGNED NOT NULL DEFAULT 23,
  actual_header_count INT UNSIGNED NOT NULL DEFAULT 0,
  header_status VARCHAR(32) NOT NULL DEFAULT 'pending',
  expected_headers_json LONGTEXT NULL,
  actual_headers_json LONGTEXT NULL,
  total_rows INT UNSIGNED NOT NULL DEFAULT 0,
  imported_rows INT UNSIGNED NOT NULL DEFAULT 0,
  skipped_rows INT UNSIGNED NOT NULL DEFAULT 0,
  malformed_rows INT UNSIGNED NOT NULL DEFAULT 0,
  duplicate_rows INT UNSIGNED NOT NULL DEFAULT 0,
  status VARCHAR(32) NOT NULL DEFAULT 'created',
  error_message TEXT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  completed_at DATETIME NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customer_import_batches_code (batch_code),
  KEY idx_customer_import_batches_created (created_at),
  KEY idx_customer_import_batches_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_pos_raw (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  batch_id BIGINT UNSIGNED NOT NULL,
  source_row_number INT UNSIGNED NOT NULL,
  source_index VARCHAR(80) NOT NULL DEFAULT '',
  member_level VARCHAR(80) NOT NULL DEFAULT '',
  member_code VARCHAR(80) NOT NULL DEFAULT '',
  member_name VARCHAR(255) NOT NULL DEFAULT '',
  member_card_no VARCHAR(120) NOT NULL DEFAULT '',
  tax_id VARCHAR(80) NOT NULL DEFAULT '',
  phone1 VARCHAR(255) NOT NULL DEFAULT '',
  phone2 VARCHAR(255) NOT NULL DEFAULT '',
  phone3 VARCHAR(255) NOT NULL DEFAULT '',
  postal_code VARCHAR(40) NOT NULL DEFAULT '',
  address_raw TEXT NULL,
  pos_uid VARCHAR(160) NOT NULL DEFAULT '',
  gender_raw VARCHAR(80) NOT NULL DEFAULT '',
  birthday_raw VARCHAR(80) NOT NULL DEFAULT '',
  company_title VARCHAR(255) NOT NULL DEFAULT '',
  note_raw TEXT NULL,
  opening_date_raw VARCHAR(80) NOT NULL DEFAULT '',
  stored_value_opening_raw VARCHAR(80) NOT NULL DEFAULT '',
  bonus_opening_raw VARCHAR(80) NOT NULL DEFAULT '',
  store_code_raw VARCHAR(80) NOT NULL DEFAULT '',
  consumption_opening_raw VARCHAR(80) NOT NULL DEFAULT '',
  email_raw VARCHAR(255) NOT NULL DEFAULT '',
  carrier_raw VARCHAR(255) NOT NULL DEFAULT '',
  bonus_accumulated_opening_raw VARCHAR(80) NOT NULL DEFAULT '',
  raw_column_count INT UNSIGNED NOT NULL DEFAULT 0,
  raw_row_json LONGTEXT NOT NULL,
  raw_row_hash CHAR(64) NOT NULL,
  import_status VARCHAR(32) NOT NULL DEFAULT 'raw_imported',
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customer_pos_raw_batch_row (batch_id, source_row_number),
  KEY idx_customer_pos_raw_batch (batch_id),
  KEY idx_customer_pos_raw_member_code (member_code),
  KEY idx_customer_pos_raw_pos_uid (pos_uid),
  KEY idx_customer_pos_raw_hash (raw_row_hash),
  KEY idx_customer_pos_raw_name (member_name(100))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customers (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  store_id VARCHAR(64) NOT NULL DEFAULT 'dawan',
  store_code VARCHAR(64) NOT NULL DEFAULT 'dawan',
  store_name VARCHAR(120) NOT NULL DEFAULT '喜樂燒臘大灣店',
  source_system VARCHAR(40) NOT NULL DEFAULT 'cashier_master',
  source_batch_id BIGINT UNSIGNED NULL,
  source_raw_id BIGINT UNSIGNED NULL,
  source_member_code VARCHAR(80) NOT NULL DEFAULT '',
  member_level VARCHAR(80) NOT NULL DEFAULT '',
  customer_name VARCHAR(255) NOT NULL DEFAULT '',
  customer_name_key VARCHAR(255) NOT NULL DEFAULT '',
  member_card_no VARCHAR(120) NOT NULL DEFAULT '',
  tax_id VARCHAR(80) NOT NULL DEFAULT '',
  pos_uid VARCHAR(160) NOT NULL DEFAULT '',
  gender_raw VARCHAR(80) NOT NULL DEFAULT '',
  birthday_raw VARCHAR(80) NOT NULL DEFAULT '',
  company_title VARCHAR(255) NOT NULL DEFAULT '',
  postal_code VARCHAR(40) NOT NULL DEFAULT '',
  email VARCHAR(255) NOT NULL DEFAULT '',
  carrier VARCHAR(255) NOT NULL DEFAULT '',
  status VARCHAR(32) NOT NULL DEFAULT 'active',
  merge_status VARCHAR(32) NOT NULL DEFAULT 'not_reviewed',
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customers_source_raw (store_id, source_system, source_raw_id),
  KEY idx_customers_source_member (store_id, source_system, source_member_code),
  KEY idx_customers_batch (source_batch_id),
  KEY idx_customers_source_raw (source_raw_id),
  KEY idx_customers_name_key (customer_name_key(120)),
  KEY idx_customers_pos_uid (pos_uid),
  KEY idx_customers_tax_id (tax_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_phones (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  customer_id BIGINT UNSIGNED NOT NULL,
  source_batch_id BIGINT UNSIGNED NULL,
  source_raw_id BIGINT UNSIGNED NULL,
  source_field VARCHAR(32) NOT NULL DEFAULT '',
  raw_phone VARCHAR(255) NOT NULL DEFAULT '',
  phone_digits VARCHAR(40) NOT NULL DEFAULT '',
  phone_last4 VARCHAR(8) NOT NULL DEFAULT '',
  extension VARCHAR(80) NOT NULL DEFAULT '',
  contact_person VARCHAR(120) NOT NULL DEFAULT '',
  phone_type VARCHAR(32) NOT NULL DEFAULT 'unknown',
  is_primary TINYINT(1) NOT NULL DEFAULT 0,
  parse_status VARCHAR(32) NOT NULL DEFAULT 'parsed',
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customer_phones_source (customer_id, source_field, raw_phone),
  KEY idx_customer_phones_customer (customer_id),
  KEY idx_customer_phones_digits (phone_digits),
  KEY idx_customer_phones_last4 (phone_last4)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_addresses (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  customer_id BIGINT UNSIGNED NOT NULL,
  source_batch_id BIGINT UNSIGNED NULL,
  source_raw_id BIGINT UNSIGNED NULL,
  source_field VARCHAR(40) NOT NULL DEFAULT '地址',
  raw_address TEXT NULL,
  normalized_address TEXT NULL,
  district VARCHAR(80) NOT NULL DEFAULT '',
  road_name VARCHAR(160) NOT NULL DEFAULT '',
  road_key VARCHAR(160) NOT NULL DEFAULT '',
  house_number VARCHAR(160) NOT NULL DEFAULT '',
  navigation_address TEXT NULL,
  delivery_note TEXT NULL,
  is_primary TINYINT(1) NOT NULL DEFAULT 1,
  parse_status VARCHAR(32) NOT NULL DEFAULT 'pending',
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_customer_addresses_customer (customer_id),
  KEY idx_customer_addresses_district_road (district, road_key),
  KEY idx_customer_addresses_batch (source_batch_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_notes (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  customer_id BIGINT UNSIGNED NOT NULL,
  source_batch_id BIGINT UNSIGNED NULL,
  source_raw_id BIGINT UNSIGNED NULL,
  note_type VARCHAR(40) NOT NULL DEFAULT 'customer_note',
  source_field VARCHAR(40) NOT NULL DEFAULT '備註',
  raw_note TEXT NULL,
  normalized_note TEXT NULL,
  status VARCHAR(32) NOT NULL DEFAULT 'active',
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_customer_notes_customer (customer_id),
  KEY idx_customer_notes_type (note_type),
  KEY idx_customer_notes_batch (source_batch_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_import_issues (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  batch_id BIGINT UNSIGNED NOT NULL,
  source_raw_id BIGINT UNSIGNED NULL,
  customer_id BIGINT UNSIGNED NULL,
  source_row_number INT UNSIGNED NOT NULL DEFAULT 0,
  issue_type VARCHAR(64) NOT NULL,
  issue_level VARCHAR(20) NOT NULL DEFAULT 'warning',
  field_name VARCHAR(80) NOT NULL DEFAULT '',
  raw_value TEXT NULL,
  normalized_value TEXT NULL,
  issue_message TEXT NULL,
  details_json LONGTEXT NULL,
  review_status VARCHAR(32) NOT NULL DEFAULT 'pending',
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  reviewed_at DATETIME NULL,
  PRIMARY KEY (id),
  KEY idx_customer_import_issues_batch (batch_id),
  KEY idx_customer_import_issues_customer (customer_id),
  KEY idx_customer_import_issues_type (issue_type),
  KEY idx_customer_import_issues_review (review_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_merge_candidates (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  batch_id BIGINT UNSIGNED NULL,
  primary_customer_id BIGINT UNSIGNED NOT NULL,
  candidate_customer_id BIGINT UNSIGNED NOT NULL,
  match_type VARCHAR(40) NOT NULL,
  match_score DECIMAL(6,2) NOT NULL DEFAULT 0,
  match_reason TEXT NULL,
  evidence_json LONGTEXT NULL,
  review_status VARCHAR(32) NOT NULL DEFAULT 'pending',
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  reviewed_at DATETIME NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customer_merge_candidates_pair (primary_customer_id, candidate_customer_id, match_type),
  KEY idx_customer_merge_candidates_batch (batch_id),
  KEY idx_customer_merge_candidates_review (review_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_merge_logs (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  merge_candidate_id BIGINT UNSIGNED NULL,
  primary_customer_id BIGINT UNSIGNED NOT NULL,
  merged_customer_id BIGINT UNSIGNED NOT NULL,
  action VARCHAR(40) NOT NULL,
  before_json LONGTEXT NULL,
  after_json LONGTEXT NULL,
  operator_name VARCHAR(120) NOT NULL DEFAULT '',
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_customer_merge_logs_primary (primary_customer_id),
  KEY idx_customer_merge_logs_merged (merged_customer_id),
  KEY idx_customer_merge_logs_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_bk_mirror (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  customer_id BIGINT UNSIGNED NOT NULL,
  source_batch_id BIGINT UNSIGNED NULL,
  bk_key VARCHAR(160) NOT NULL,
  source VARCHAR(40) NOT NULL DEFAULT 'cashier_master',
  customer_code VARCHAR(80) NOT NULL DEFAULT '',
  customer_name VARCHAR(255) NOT NULL DEFAULT '',
  phone VARCHAR(255) NOT NULL DEFAULT '',
  phone_digits VARCHAR(40) NOT NULL DEFAULT '',
  phone_last4 VARCHAR(8) NOT NULL DEFAULT '',
  address TEXT NULL,
  customer_address TEXT NULL,
  delivery_address TEXT NULL,
  actual_delivery_address TEXT NULL,
  navigation_address TEXT NULL,
  map_address TEXT NULL,
  note TEXT NULL,
  search_text TEXT NULL,
  raw_payload_json LONGTEXT NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customer_bk_mirror_customer (customer_id),
  UNIQUE KEY uq_customer_bk_mirror_key (bk_key),
  KEY idx_customer_bk_mirror_batch (source_batch_id),
  KEY idx_customer_bk_mirror_phone (phone_digits),
  KEY idx_customer_bk_mirror_last4 (phone_last4),
  KEY idx_customer_bk_mirror_name (customer_name(100))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_address_cache (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  store_id VARCHAR(64) NOT NULL DEFAULT 'dawan',
  district VARCHAR(80) NOT NULL,
  road_name VARCHAR(160) NOT NULL,
  road_key VARCHAR(160) NOT NULL,
  address_count INT UNSIGNED NOT NULL DEFAULT 0,
  sort_order INT UNSIGNED NOT NULL DEFAULT 0,
  source VARCHAR(80) NOT NULL DEFAULT 'customer_bk_mirror',
  raw_variants_json LONGTEXT NULL,
  last_used_at DATETIME NULL,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customer_address_cache_road (store_id, district, road_key),
  KEY idx_customer_address_cache_rank (store_id, district, address_count, sort_order),
  KEY idx_customer_address_cache_road_key (road_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_pipeline_runs (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  batch_id BIGINT UNSIGNED NULL,
  run_type VARCHAR(64) NOT NULL,
  status VARCHAR(32) NOT NULL DEFAULT 'running',
  stats_json LONGTEXT NULL,
  error_message TEXT NULL,
  started_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  completed_at DATETIME NULL,
  PRIMARY KEY (id),
  KEY idx_customer_pipeline_runs_batch (batch_id),
  KEY idx_customer_pipeline_runs_type (run_type),
  KEY idx_customer_pipeline_runs_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


CREATE TABLE IF NOT EXISTS customer_bk_import_batches (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  batch_code VARCHAR(64) NOT NULL,
  source_system VARCHAR(40) NOT NULL DEFAULT 'delivery_bk',
  firebase_project_id VARCHAR(120) NOT NULL DEFAULT '',
  firebase_database_url VARCHAR(255) NOT NULL DEFAULT '',
  firebase_uid VARCHAR(160) NOT NULL DEFAULT '',
  firebase_email VARCHAR(255) NOT NULL DEFAULT '',
  customers_count INT UNSIGNED NOT NULL DEFAULT 0,
  temp_customers_count INT UNSIGNED NOT NULL DEFAULT 0,
  delivery_tasks_count INT UNSIGNED NOT NULL DEFAULT 0,
  expected_records INT UNSIGNED NOT NULL DEFAULT 0,
  imported_records INT UNSIGNED NOT NULL DEFAULT 0,
  duplicate_records INT UNSIGNED NOT NULL DEFAULT 0,
  status VARCHAR(32) NOT NULL DEFAULT 'created',
  summary_json LONGTEXT NULL,
  error_message TEXT NULL,
  started_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  completed_at DATETIME NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customer_bk_import_batches_code (batch_code),
  KEY idx_customer_bk_import_batches_status (status),
  KEY idx_customer_bk_import_batches_started (started_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_bk_raw_records (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  batch_id BIGINT UNSIGNED NOT NULL,
  source_node VARCHAR(32) NOT NULL,
  source_key VARCHAR(160) NOT NULL,
  store_id VARCHAR(64) NOT NULL DEFAULT 'dawan',
  store_code VARCHAR(64) NOT NULL DEFAULT 'dawan',
  store_name VARCHAR(120) NOT NULL DEFAULT '喜樂燒臘大灣店',
  customer_key VARCHAR(160) NOT NULL DEFAULT '',
  temp_customer_key VARCHAR(160) NOT NULL DEFAULT '',
  customer_code VARCHAR(80) NOT NULL DEFAULT '',
  source_kind VARCHAR(40) NOT NULL DEFAULT '',
  customer_name VARCHAR(255) NOT NULL DEFAULT '',
  customer_name_key VARCHAR(255) NOT NULL DEFAULT '',
  phone VARCHAR(255) NOT NULL DEFAULT '',
  phone_digits VARCHAR(40) NOT NULL DEFAULT '',
  phone_last4 VARCHAR(8) NOT NULL DEFAULT '',
  address TEXT NULL,
  customer_address TEXT NULL,
  delivery_address TEXT NULL,
  actual_delivery_address TEXT NULL,
  navigation_address TEXT NULL,
  map_address TEXT NULL,
  address_key VARCHAR(255) NOT NULL DEFAULT '',
  note TEXT NULL,
  customer_note TEXT NULL,
  order_summary TEXT NULL,
  needs_pos_merge TINYINT(1) NOT NULL DEFAULT 0,
  pos_merge_status VARCHAR(32) NOT NULL DEFAULT '',
  status_raw VARCHAR(32) NOT NULL DEFAULT '',
  is_temp_customer TINYINT(1) NOT NULL DEFAULT 0,
  task_date_key VARCHAR(32) NOT NULL DEFAULT '',
  last_task_id VARCHAR(160) NOT NULL DEFAULT '',
  created_at_raw BIGINT NOT NULL DEFAULT 0,
  updated_at_raw BIGINT NOT NULL DEFAULT 0,
  last_used_at_raw BIGINT NOT NULL DEFAULT 0,
  raw_json LONGTEXT NOT NULL,
  raw_hash CHAR(64) NOT NULL,
  imported_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customer_bk_raw_record (batch_id, source_node, source_key),
  KEY idx_customer_bk_raw_batch_node (batch_id, source_node),
  KEY idx_customer_bk_raw_phone (phone_digits),
  KEY idx_customer_bk_raw_customer_key (customer_key),
  KEY idx_customer_bk_raw_temp_key (temp_customer_key),
  KEY idx_customer_bk_raw_name_key (customer_name_key(120)),
  KEY idx_customer_bk_raw_hash (raw_hash)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_source_links (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  source_system VARCHAR(40) NOT NULL DEFAULT 'delivery_bk',
  source_batch_id BIGINT UNSIGNED NOT NULL,
  pos_batch_id BIGINT UNSIGNED NULL,
  profile_key VARCHAR(160) NOT NULL,
  profile_type VARCHAR(40) NOT NULL,
  primary_source_node VARCHAR(32) NOT NULL DEFAULT '',
  primary_source_key VARCHAR(160) NOT NULL DEFAULT '',
  customer_id BIGINT UNSIGNED NULL,
  display_name VARCHAR(255) NOT NULL DEFAULT '',
  display_phone VARCHAR(255) NOT NULL DEFAULT '',
  display_address TEXT NULL,
  phone_digits VARCHAR(40) NOT NULL DEFAULT '',
  customer_name_key VARCHAR(255) NOT NULL DEFAULT '',
  address_key VARCHAR(255) NOT NULL DEFAULT '',
  match_status VARCHAR(40) NOT NULL DEFAULT 'pending',
  match_method VARCHAR(80) NOT NULL DEFAULT '',
  match_score DECIMAL(6,2) NOT NULL DEFAULT 0,
  evidence_json LONGTEXT NULL,
  review_status VARCHAR(32) NOT NULL DEFAULT 'pending',
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customer_source_links_profile (source_batch_id, profile_key),
  KEY idx_customer_source_links_customer (customer_id),
  KEY idx_customer_source_links_status (source_batch_id, match_status),
  KEY idx_customer_source_links_phone (phone_digits),
  KEY idx_customer_source_links_review (review_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_source_match_candidates (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  source_batch_id BIGINT UNSIGNED NOT NULL,
  pos_batch_id BIGINT UNSIGNED NULL,
  profile_key VARCHAR(160) NOT NULL,
  customer_id BIGINT UNSIGNED NOT NULL,
  match_type VARCHAR(60) NOT NULL,
  match_score DECIMAL(6,2) NOT NULL DEFAULT 0,
  phone_match TINYINT(1) NOT NULL DEFAULT 0,
  member_code_match TINYINT(1) NOT NULL DEFAULT 0,
  name_match TINYINT(1) NOT NULL DEFAULT 0,
  address_match TINYINT(1) NOT NULL DEFAULT 0,
  conflict_flags_json LONGTEXT NULL,
  evidence_json LONGTEXT NULL,
  review_status VARCHAR(32) NOT NULL DEFAULT 'pending',
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customer_source_match_candidate (source_batch_id, profile_key, customer_id),
  KEY idx_customer_source_match_profile (source_batch_id, profile_key),
  KEY idx_customer_source_match_customer (customer_id),
  KEY idx_customer_source_match_review (review_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_export_runs (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  export_code VARCHAR(64) NOT NULL,
  export_type VARCHAR(32) NOT NULL DEFAULT 'full',
  target_format VARCHAR(40) NOT NULL DEFAULT 'cashier_master_23',
  target_encoding VARCHAR(32) NOT NULL DEFAULT 'CP950',
  source_snapshot_at DATETIME NULL,
  total_customers INT UNSIGNED NOT NULL DEFAULT 0,
  valid_rows INT UNSIGNED NOT NULL DEFAULT 0,
  invalid_rows INT UNSIGNED NOT NULL DEFAULT 0,
  status VARCHAR(32) NOT NULL DEFAULT 'draft',
  validation_json LONGTEXT NULL,
  created_by VARCHAR(160) NOT NULL DEFAULT '',
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  completed_at DATETIME NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customer_export_runs_code (export_code),
  KEY idx_customer_export_runs_status (status),
  KEY idx_customer_export_runs_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_export_rows (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  export_run_id BIGINT UNSIGNED NOT NULL,
  customer_id BIGINT UNSIGNED NOT NULL,
  member_code VARCHAR(80) NOT NULL DEFAULT '',
  export_row_number INT UNSIGNED NOT NULL DEFAULT 0,
  output_row_json LONGTEXT NOT NULL,
  validation_status VARCHAR(32) NOT NULL DEFAULT 'pending',
  validation_message TEXT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customer_export_rows_customer (export_run_id, customer_id),
  KEY idx_customer_export_rows_run (export_run_id),
  KEY idx_customer_export_rows_status (validation_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


CREATE TABLE IF NOT EXISTS customer_external_sources (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  source_code VARCHAR(64) NOT NULL,
  source_name VARCHAR(160) NOT NULL,
  source_type VARCHAR(64) NOT NULL DEFAULT 'firebase_rtdb',
  project_id VARCHAR(160) NOT NULL DEFAULT '',
  database_url VARCHAR(255) NOT NULL DEFAULT '',
  allowed_nodes_json LONGTEXT NULL,
  is_enabled TINYINT(1) NOT NULL DEFAULT 1,
  write_back_enabled TINYINT(1) NOT NULL DEFAULT 0,
  connection_status VARCHAR(40) NOT NULL DEFAULT 'not_checked',
  last_success_at DATETIME NULL,
  last_error_at DATETIME NULL,
  last_checked_at DATETIME NULL,
  last_error_code VARCHAR(80) NOT NULL DEFAULT '',
  last_error_message TEXT NULL,
  config_json LONGTEXT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customer_external_sources_code (source_code),
  KEY idx_customer_external_sources_enabled (is_enabled),
  KEY idx_customer_external_sources_status (connection_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_source_authorizations (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  authorization_code VARCHAR(80) NOT NULL,
  source_id BIGINT UNSIGNED NOT NULL,
  source_code VARCHAR(64) NOT NULL,
  operator_uid VARCHAR(160) NOT NULL DEFAULT '',
  operator_email VARCHAR(255) NOT NULL DEFAULT '',
  operator_name VARCHAR(160) NOT NULL DEFAULT '',
  operator_role VARCHAR(64) NOT NULL DEFAULT '',
  purpose VARCHAR(500) NOT NULL DEFAULT '',
  allowed_nodes_json LONGTEXT NOT NULL,
  allowed_actions_json LONGTEXT NOT NULL,
  validity_mode VARCHAR(32) NOT NULL DEFAULT 'session',
  grant_token_hash CHAR(64) NOT NULL,
  grant_token_last4 VARCHAR(8) NOT NULL DEFAULT '',
  session_hash CHAR(64) NOT NULL,
  status VARCHAR(32) NOT NULL DEFAULT 'active',
  expires_at DATETIME NOT NULL,
  last_used_at DATETIME NULL,
  revoked_at DATETIME NULL,
  revoked_by VARCHAR(160) NOT NULL DEFAULT '',
  revocation_reason VARCHAR(500) NOT NULL DEFAULT '',
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customer_source_authorizations_code (authorization_code),
  UNIQUE KEY uq_customer_source_authorizations_token (grant_token_hash),
  KEY idx_customer_source_authorizations_source (source_id,status),
  KEY idx_customer_source_authorizations_operator (operator_uid,status),
  KEY idx_customer_source_authorizations_expiry (expires_at,status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS customer_source_access_logs (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  request_id VARCHAR(80) NOT NULL,
  authorization_id BIGINT UNSIGNED NULL,
  source_id BIGINT UNSIGNED NULL,
  source_code VARCHAR(64) NOT NULL DEFAULT '',
  operator_uid VARCHAR(160) NOT NULL DEFAULT '',
  operator_email VARCHAR(255) NOT NULL DEFAULT '',
  operator_role VARCHAR(64) NOT NULL DEFAULT '',
  action_name VARCHAR(64) NOT NULL,
  requested_nodes_json LONGTEXT NULL,
  result_status VARCHAR(32) NOT NULL DEFAULT 'unknown',
  http_status INT NOT NULL DEFAULT 0,
  records_count INT UNSIGNED NOT NULL DEFAULT 0,
  node_counts_json LONGTEXT NULL,
  error_code VARCHAR(100) NOT NULL DEFAULT '',
  error_message TEXT NULL,
  session_hash CHAR(64) NOT NULL DEFAULT '',
  client_ip_hash CHAR(64) NOT NULL DEFAULT '',
  user_agent VARCHAR(500) NOT NULL DEFAULT '',
  duration_ms INT UNSIGNED NOT NULL DEFAULT 0,
  details_json LONGTEXT NULL,
  started_at DATETIME NOT NULL,
  completed_at DATETIME NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_customer_source_access_logs_request (request_id),
  KEY idx_customer_source_access_logs_source (source_id,created_at),
  KEY idx_customer_source_access_logs_authorization (authorization_id,created_at),
  KEY idx_customer_source_access_logs_operator (operator_uid,created_at),
  KEY idx_customer_source_access_logs_result (result_status,error_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
