CREATE TABLE drive_org_folders (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    org_slug TEXT NOT NULL,
    nc_folder_id INTEGER NOT NULL,
    mount_point TEXT NOT NULL,
    quota_bytes BIGINT,
    auto_provisioned BOOLEAN NOT NULL DEFAULT false,
    created_by TEXT NOT NULL DEFAULT '',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT drive_org_folders_org_slug_uniq UNIQUE (org_slug),
    CONSTRAINT drive_org_folders_nc_folder_id_uniq UNIQUE (nc_folder_id)
);

CREATE INDEX idx_drive_org_folders_org_slug ON drive_org_folders (org_slug);

CREATE TABLE drive_mounts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    scope TEXT NOT NULL CHECK (scope IN ('user', 'org')),
    owner_user_id UUID REFERENCES users(id) ON DELETE CASCADE,
    org_slug TEXT,
    nc_mount_id INTEGER,
    display_name TEXT NOT NULL,
    backend_type TEXT NOT NULL,
    mount_point TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'error', 'pending')),
    last_error TEXT NOT NULL DEFAULT '',
    config_encrypted BYTEA,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT drive_mounts_scope_owner_chk CHECK (
        (scope = 'user' AND owner_user_id IS NOT NULL)
        OR (scope = 'org' AND org_slug IS NOT NULL AND org_slug <> '')
    )
);

CREATE INDEX idx_drive_mounts_owner ON drive_mounts (owner_user_id) WHERE scope = 'user';
CREATE INDEX idx_drive_mounts_org ON drive_mounts (org_slug) WHERE scope = 'org';
