-- 商品编号：用于前台展示、搜索和客服定位
ALTER TABLE rental_listings
  ADD COLUMN listing_no VARCHAR(20) NULL COMMENT '商品编号，格式yyyyMMddNNNN' AFTER id;

UPDATE rental_listings AS l
JOIN (
  SELECT
    id,
    CONCAT(
      DATE_FORMAT(created_at, '%Y%m%d'),
      LPAD(ROW_NUMBER() OVER (PARTITION BY DATE(created_at) ORDER BY id), 4, '0')
    ) AS generated_listing_no
  FROM rental_listings
) AS seq ON seq.id = l.id
SET l.listing_no = seq.generated_listing_no
WHERE l.listing_no IS NULL OR l.listing_no = '';

ALTER TABLE rental_listings
  MODIFY COLUMN listing_no VARCHAR(20) NOT NULL COMMENT '商品编号，格式yyyyMMddNNNN',
  ADD UNIQUE KEY uk_rental_listings_listing_no (listing_no);

CREATE TABLE IF NOT EXISTS listing_no_sequences (
  biz_date CHAR(8) PRIMARY KEY COMMENT '业务日期yyyyMMdd',
  next_seq INT NOT NULL DEFAULT 0 COMMENT '当日已分配最大序号',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='商品编号日序列表';

INSERT INTO listing_no_sequences (biz_date, next_seq)
SELECT DATE_FORMAT(created_at, '%Y%m%d') AS biz_date, COUNT(*) AS next_seq
FROM rental_listings
GROUP BY DATE_FORMAT(created_at, '%Y%m%d')
ON DUPLICATE KEY UPDATE next_seq = GREATEST(next_seq, VALUES(next_seq));
