-- Permissions plugin initial migration: creates permissions and share_links tables
CREATE TABLE IF NOT EXISTS permissions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    file_id UUID NOT NULL,
    user_id UUID NOT NULL,
    group_id UUID,
    access_level VARCHAR(10) NOT NULL DEFAULT 'read',
    deleted_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    CONSTRAINT uq_permissions_file_user_level UNIQUE (tenant_id, file_id, user_id, access_level)
);
CREATE INDEX IF NOT EXISTS ix_permissions_file ON permissions(tenant_id, file_id);
CREATE INDEX IF NOT EXISTS ix_permissions_user ON permissions(tenant_id, user_id);

CREATE TABLE IF NOT EXISTS share_links (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    file_id UUID NOT NULL,
    token VARCHAR(64) NOT NULL UNIQUE,
    password_hash VARCHAR(255),
    expires_at TIMESTAMPTZ,
    access_level VARCHAR(10) NOT NULL DEFAULT 'download',
    created_by UUID,
    deleted_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX IF NOT EXISTS ix_share_links_token ON share_links(token);
CREATE INDEX IF NOT EXISTS ix_share_links_file ON share_links(tenant_id, file_id);
