-- 素材主表
CREATE TABLE materials (
    id BIGSERIAL PRIMARY KEY,
    oss_key VARCHAR(255) NOT NULL,
    original_name VARCHAR(255) NOT NULL,
    file_size BIGINT NOT NULL,
    mime_type VARCHAR(100) NOT NULL,
    width INT,
    height INT,
    hash VARCHAR(64) NOT NULL,
    created_by BIGINT NOT NULL,
    star_id BIGINT NOT NULL DEFAULT 0,
    created_at BIGINT NOT NULL,
    updated_at BIGINT NOT NULL,
    deleted_at BIGINT
);

CREATE UNIQUE INDEX uk_materials_oss_key ON materials(oss_key);
CREATE INDEX idx_materials_hash ON materials(hash);
CREATE INDEX idx_materials_created_by ON materials(created_by);
CREATE INDEX idx_materials_star_id ON materials(star_id);

-- 资产-素材关联表
CREATE TABLE asset_material_relations (
    id BIGSERIAL PRIMARY KEY,
    asset_id BIGINT NOT NULL REFERENCES assets(id) ON DELETE CASCADE,
    material_id BIGINT NOT NULL REFERENCES materials(id) ON DELETE RESTRICT,
    material_type VARCHAR(50) NOT NULL,
    layer_order INT NOT NULL DEFAULT 0,
    pos_x DOUBLE PRECISION,
    pos_y DOUBLE PRECISION,
    opacity DOUBLE PRECISION DEFAULT 1.0,
    rotation DOUBLE PRECISION DEFAULT 0,
    scale_x DOUBLE PRECISION DEFAULT 1.0,
    scale_y DOUBLE PRECISION DEFAULT 1.0,
    version INT NOT NULL DEFAULT 1,
    created_at BIGINT NOT NULL,
    updated_at BIGINT NOT NULL,
    deleted_at BIGINT
);

-- 索引
CREATE INDEX idx_amr_asset_id ON asset_material_relations(asset_id) WHERE deleted_at IS NULL;
CREATE INDEX idx_amr_material_id ON asset_material_relations(material_id) WHERE deleted_at IS NULL;
CREATE INDEX idx_amr_asset_type_layer ON asset_material_relations(asset_id, material_type, layer_order) WHERE deleted_at IS NULL;

-- 部分唯一索引（软删除感知）
CREATE UNIQUE INDEX uk_amr_asset_type_active ON asset_material_relations(asset_id, material_type) WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX uk_amr_asset_layer_active ON asset_material_relations(asset_id, layer_order) WHERE deleted_at IS NULL;
