create table if not exists customers (
  id integer primary key,
  username text not null unique,
  receipt text not null unique,
  billing_email text,
  invitation id,
  created_at int not null default (unixepoch()),
  updated_at int not null default (unixepoch()),
  foreign key (invitation) references invitations (id)
);
create index if not exists customers_username_dex on customers (lower(username));
create index if not exists customers_email_dex on customers (lower(billing_email));
create index if not exists customers_receipt_dex on customers (receipt);
create index if not exists customers_invitation_dex on customers (invitation); -- does this need to be created? it's already a foreign key

create trigger if not exists update_last_updated_customers
  after update on customers
  when OLD.updated_at = NEW.updated_at or OLD.updated_at is null
BEGIN
  update customers set updated_at = (select unixepoch()) where id=NEW.id;
END;


create table if not exists invitations (
  id integer primary key,
  owner integer not null,
  remaining integer not null default 1,
  expires_at integer,
  created_at integer not null default (unixepoch()),
  updated_at integer not null default (unixepoch()),
  foreign key (owner) references customers (id)
);
create index if not exists invitations_owner_dex on invitations (owner);

create trigger if not exists update_updated_at_invitations
  after update on invitations
  when OLD.updated_at = NEW.updated_at or OLD.updated_at is null
BEGIN
  update invitations set updated_at = (select unixepoch()) where id=NEW.id;
END;

