-- 迁移: 创建企业设备授权表
-- 说明:
--   1. 创建 tb_enterprise_device_authorization 表，记录设备与企业的授权关系
--   2. 添加部分唯一索引保证一个设备同时只能授权给一个企业
--   3. 添加常规索引优化查询性能

CREATE TABLE IF NOT EXISTS tb_enterprise_device_authorization (
    id BIGSERIAL PRIMARY KEY,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP,
    enterprise_id BIGINT NOT NULL,
    device_id BIGINT NOT NULL,
    authorized_by BIGINT NOT NULL,
    authorized_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    authorizer_type SMALLINT NOT NULL,
    revoked_by BIGINT,
    revoked_at TIMESTAMP,
    remark VARCHAR(500) DEFAULT ''
);

-- 添加部分唯一索引：一个设备同时只能授权给一个企业
CREATE UNIQUE INDEX IF NOT EXISTS uq_active_device_auth 
ON tb_enterprise_device_authorization(device_id) 
WHERE revoked_at IS NULL AND deleted_at IS NULL;

-- 添加常规索引
CREATE INDEX IF NOT EXISTS idx_eda_enterprise ON tb_enterprise_device_authorization(enterprise_id);
CREATE INDEX IF NOT EXISTS idx_eda_device ON tb_enterprise_device_authorization(device_id);
CREATE INDEX IF NOT EXISTS idx_eda_authorized_by ON tb_enterprise_device_authorization(authorized_by);
CREATE INDEX IF NOT EXISTS idx_eda_deleted_at ON tb_enterprise_device_authorization(deleted_at);

-- 添加表注释
COMMENT ON TABLE tb_enterprise_device_authorization IS '企业设备授权表';

-- 添加字段注释
COMMENT ON COLUMN tb_enterprise_device_authorization.id IS '主键ID';
COMMENT ON COLUMN tb_enterprise_device_authorization.created_at IS '创建时间';
COMMENT ON COLUMN tb_enterprise_device_authorization.updated_at IS '更新时间';
COMMENT ON COLUMN tb_enterprise_device_authorization.deleted_at IS '软删除时间';
COMMENT ON COLUMN tb_enterprise_device_authorization.enterprise_id IS '被授权企业ID';
COMMENT ON COLUMN tb_enterprise_device_authorization.device_id IS '被授权设备ID';
COMMENT ON COLUMN tb_enterprise_device_authorization.authorized_by IS '授权人账号ID';
COMMENT ON COLUMN tb_enterprise_device_authorization.authorized_at IS '授权时间';
COMMENT ON COLUMN tb_enterprise_device_authorization.authorizer_type IS '授权人类型：2=平台用户 3=代理账号';
COMMENT ON COLUMN tb_enterprise_device_authorization.revoked_by IS '回收人账号ID';
COMMENT ON COLUMN tb_enterprise_device_authorization.revoked_at IS '回收时间';
COMMENT ON COLUMN tb_enterprise_device_authorization.remark IS '授权备注';
