-- +goose Up
-- +goose StatementBegin

INSERT INTO permissions (code, name, resource, action) VALUES
('chat:manage', '管理客服配置', 'chat', 'manage')
ON DUPLICATE KEY UPDATE
  name = VALUES(name),
  resource = VALUES(resource),
  action = VALUES(action);

INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p ON p.code = 'chat:manage'
WHERE r.code = 'super_admin';

CREATE TABLE IF NOT EXISTS chat_support_groups (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  code VARCHAR(64) NOT NULL COMMENT '固定业务编码: owner_onboarding/renter_handoff',
  name VARCHAR(64) NOT NULL COMMENT '客服分组名称',
  description VARCHAR(255) NOT NULL DEFAULT '' COMMENT '分组说明',
  status VARCHAR(16) NOT NULL DEFAULT 'active' COMMENT '状态: active/disabled',
  sort_order 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,
  UNIQUE KEY uk_chat_support_groups_code (code),
  KEY idx_chat_support_groups_status_sort (status, sort_order, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='客服分组表';

CREATE TABLE IF NOT EXISTS chat_support_group_members (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  group_id BIGINT UNSIGNED NOT NULL COMMENT '客服分组ID',
  admin_user_id BIGINT UNSIGNED NOT NULL COMMENT '管理员ID',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uk_support_group_member (group_id, admin_user_id),
  KEY idx_support_group_members_admin (admin_user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='客服分组成员表';

INSERT INTO chat_support_groups (code, name, description, status, sort_order) VALUES
('owner_onboarding', '收号组-客服', '负责用户发布后的收号沟通、拉群和入群引导', 'active', 10),
('renter_handoff', '卖号组-客服', '负责租客支付后的交接跟进和售后沟通', 'active', 20)
ON DUPLICATE KEY UPDATE
  name = VALUES(name),
  description = VALUES(description),
  sort_order = VALUES(sort_order);

INSERT IGNORE INTO chat_support_group_members (group_id, admin_user_id)
SELECT g.id, au.id
FROM chat_support_groups g
JOIN admin_user_roles aur ON 1 = 1
JOIN roles r ON r.id = aur.role_id
JOIN admin_users au ON au.id = aur.admin_user_id
WHERE g.code IN ('owner_onboarding', 'renter_handoff')
  AND r.code = 'cs'
  AND au.status = 'active';

INSERT INTO system_configs (`key`, `value`, description) VALUES
('chat.renter_retention_days_after_order_end', '5', '订单结束后租客保留在发布群的天数（3-7）')
ON DUPLICATE KEY UPDATE
  description = VALUES(description);

-- +goose StatementEnd

-- +goose Down
-- +goose StatementBegin

DROP TABLE IF EXISTS chat_support_group_members;
DROP TABLE IF EXISTS chat_support_groups;
DELETE rp FROM role_permissions rp
JOIN permissions p ON p.id = rp.permission_id
WHERE p.code = 'chat:manage';
DELETE FROM permissions WHERE code = 'chat:manage';
DELETE FROM system_configs WHERE `key` = 'chat.renter_retention_days_after_order_end';

-- +goose StatementEnd
