CREATE TABLE multipart_uploads (
    id           UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    bucket_id    UUID NOT NULL REFERENCES buckets(id) ON DELETE CASCADE,
    key          TEXT NOT NULL,
    upload_id    TEXT NOT NULL,
    content_type TEXT NOT NULL DEFAULT 'application/octet-stream',
    created_at   TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE UNIQUE INDEX idx_multipart_upload_id ON multipart_uploads (upload_id);
CREATE INDEX idx_multipart_bucket ON multipart_uploads (bucket_id);

CREATE TABLE multipart_upload_metadata (
    id         UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    upload_id  UUID NOT NULL REFERENCES multipart_uploads(id) ON DELETE CASCADE,
    meta_key   TEXT NOT NULL,
    meta_value TEXT NOT NULL
);
CREATE UNIQUE INDEX idx_mp_meta_key ON multipart_upload_metadata (upload_id, meta_key);

CREATE TABLE upload_parts (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    upload_id   UUID NOT NULL REFERENCES multipart_uploads(id) ON DELETE CASCADE,
    part_number INT NOT NULL,
    data        BYTEA NOT NULL,
    size        BIGINT NOT NULL,
    etag        TEXT NOT NULL,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE UNIQUE INDEX idx_upload_parts_num ON upload_parts (upload_id, part_number);
