CREATE TABLE IF NOT EXISTS qipai_franchise_applications (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  tenant_id BIGINT UNSIGNED NOT NULL,
  application_no VARCHAR(64) NOT NULL,
  client_request_id VARCHAR(128) NOT NULL,
  city VARCHAR(64) NOT NULL,
  contact_name VARCHAR(64) NOT NULL,
  contact_phone VARCHAR(32) NOT NULL,
  message VARCHAR(1000) NOT NULL DEFAULT '',
  source VARCHAR(32) NOT NULL DEFAULT 'MINIAPP',
  status VARCHAR(32) NOT NULL DEFAULT 'NEW',
  assignee_user_id BIGINT UNSIGNED NULL,
  submitted_user_id BIGINT UNSIGNED NULL,
  next_follow_up_at DATETIME(3) NULL,
  closed_at DATETIME(3) NULL,
  created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  deleted_at DATETIME(3) NULL,
  CONSTRAINT fk_qipai_franchise_application_tenant FOREIGN KEY (tenant_id) REFERENCES qipai_tenants(id),
  CONSTRAINT fk_qipai_franchise_application_assignee FOREIGN KEY (assignee_user_id) REFERENCES qipai_users(id),
  CONSTRAINT fk_qipai_franchise_application_submitter FOREIGN KEY (submitted_user_id) REFERENCES qipai_users(id),
  UNIQUE KEY uq_qipai_franchise_application_no (tenant_id, application_no),
  UNIQUE KEY uq_qipai_franchise_client_request (tenant_id, client_request_id),
  KEY idx_qipai_franchise_queue (tenant_id, status, assignee_user_id, created_at),
  KEY idx_qipai_franchise_follow_up (tenant_id, next_follow_up_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS qipai_franchise_follow_ups (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  tenant_id BIGINT UNSIGNED NOT NULL,
  application_id BIGINT UNSIGNED NOT NULL,
  actor_user_id BIGINT UNSIGNED NOT NULL,
  follow_up_type VARCHAR(32) NOT NULL,
  from_status VARCHAR(32) NULL,
  to_status VARCHAR(32) NULL,
  note VARCHAR(1000) NOT NULL,
  next_follow_up_at DATETIME(3) NULL,
  created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  CONSTRAINT fk_qipai_franchise_follow_up_tenant FOREIGN KEY (tenant_id) REFERENCES qipai_tenants(id),
  CONSTRAINT fk_qipai_franchise_follow_up_application FOREIGN KEY (application_id) REFERENCES qipai_franchise_applications(id),
  CONSTRAINT fk_qipai_franchise_follow_up_actor FOREIGN KEY (actor_user_id) REFERENCES qipai_users(id),
  KEY idx_qipai_franchise_follow_up_history (tenant_id, application_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT IGNORE INTO qipai_schema_migrations (version, name)
VALUES ('2026081003', 'm08d_franchise_leads');
