-- +goose Up

CREATE TABLE operating_expenses (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  expense_no VARCHAR(64) NOT NULL COMMENT '运营开支单号',
  category VARCHAR(50) NOT NULL COMMENT '开支类别',
  payee_name VARCHAR(100) NOT NULL COMMENT '收款方或单位名称',
  amount_cent BIGINT NOT NULL COMMENT '开支金额(分)',
  occurred_at DATETIME NOT NULL COMMENT '实际开支时间',
  remark VARCHAR(500) NOT NULL COMMENT '开支用途备注',
  voucher_url VARCHAR(500) NOT NULL DEFAULT '' COMMENT '开支凭证地址',
  status VARCHAR(16) NOT NULL DEFAULT 'paid' COMMENT '状态: paid已记账/voided已作废',
  created_by BIGINT UNSIGNED NOT NULL COMMENT '录入管理员ID',
  voided_by BIGINT UNSIGNED NULL COMMENT '作废管理员ID',
  voided_at DATETIME NULL COMMENT '作废时间',
  void_reason VARCHAR(255) NOT NULL DEFAULT '' COMMENT '作废原因',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uk_operating_expenses_no (expense_no),
  KEY idx_operating_expenses_occurred (status, occurred_at),
  KEY idx_operating_expenses_created (created_at),
  KEY idx_operating_expenses_category (category)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='运营开支记账';

INSERT INTO permissions (code, name, resource, action) VALUES
('finance:operating_expense', '管理运营开支', 'finance', 'operating_expense')
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, permissions p
WHERE r.code IN ('super_admin', 'finance') AND p.code = 'finance:operating_expense';

-- +goose Down

DELETE rp FROM role_permissions rp
JOIN permissions p ON p.id = rp.permission_id
WHERE p.code = 'finance:operating_expense';

DELETE FROM permissions WHERE code = 'finance:operating_expense';
DROP TABLE IF EXISTS operating_expenses;
