-- Credit Limit Table for accounting module
-- Run this DDL on the sage database to create the credit_limit table

CREATE TABLE IF NOT EXISTS credit_limit (
  id VARCHAR(32) NOT NULL COMMENT '主键ID',
  accountid VARCHAR(32) NOT NULL COMMENT '账户ID',
  orgid VARCHAR(32) NOT NULL COMMENT '机构ID',
  credit_limit DECIMAL(18,2) NOT NULL DEFAULT 0.00 COMMENT '信用额度',
  used_credit DECIMAL(18,2) NOT NULL DEFAULT 0.00 COMMENT '已用额度',
  available_credit DECIMAL(18,2) NOT NULL DEFAULT 0.00 COMMENT '可用额度',
  valid_from DATE COMMENT '生效日期',
  valid_to DATE COMMENT '失效日期',
  status VARCHAR(10) NOT NULL DEFAULT 'active' COMMENT '状态',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL COMMENT '创建时间',
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL COMMENT '更新时间',
  created_by VARCHAR(32) COMMENT '创建人',
  remark VARCHAR(500) COMMENT '备注',
  PRIMARY KEY (id),
  UNIQUE INDEX idx_credit_limit_account (accountid),
  INDEX idx_credit_limit_orgid (orgid),
  INDEX idx_credit_limit_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Insert credit_status codes into appcodes_kv
INSERT IGNORE INTO appcodes_kv (parentid, k, v) VALUES ('credit_status', 'active', '生效');
INSERT IGNORE INTO appcodes_kv (parentid, k, v) VALUES ('credit_status', 'inactive', '停用');
INSERT IGNORE INTO appcodes_kv (parentid, k, v) VALUES ('credit_status', 'expired', '已过期');
