-- Albums gain an owner: the tenancy root. Photos, shares, ratings and tags
-- all hang off albums, so this single column scopes everything.
alter table albums add column owner_id uuid references users(id);

-- Backfill: pre-tenancy albums had no owner. Assigning them to "the" original
-- photographer is only unambiguous when exactly one user exists. With several
-- (v0.1.0 let every allowed email share all albums) the correct owner is
-- unknowable, so refuse rather than silently transfer everyone's work to one
-- account — the operator must assign ownership manually before migrating.
do $$
declare
    n_users int;
    n_albums int;
begin
    select count(*) into n_users from users;
    select count(*) into n_albums from albums;
    if n_albums > 0 and n_users <> 1 then
        raise exception
            'multi-tenant migration: % albums exist but there are % users (need exactly 1 to auto-assign ownership); set albums.owner_id manually first',
            n_albums, n_users;
    end if;
    update albums set owner_id = (select id from users order by created_at limit 1);
end $$;

alter table albums alter column owner_id set not null;

create index albums_owner_idx on albums (owner_id);
