create table if not exists tenants (
    id text primary key,
    name text not null unique,
    created_at timestamptz not null default now()
);

create table if not exists tenant_users (
    id text primary key,
    tenant_id text not null references tenants(id),
    name text not null,
    email text,
    created_at timestamptz not null default now(),
    unique (tenant_id, email)
);

create index if not exists tenant_users_tenant_id_idx on tenant_users (tenant_id);

create table if not exists api_key_assignments (
    key_id text primary key,
    tenant_id text not null references tenants(id),
    user_id text references tenant_users(id),
    description text not null default '',
    source text not null check (source in ('configured', 'managed')),
    enabled boolean not null default true,
    created_at timestamptz not null default now()
);

create table if not exists managed_api_keys (
    key_id text primary key references api_key_assignments(key_id) on delete cascade,
    secret_hash text not null
);
