CREATE TYPE member_state AS ENUM ('normal', 'pending', 'withdrawal', 'dormancy', 'blacklist', 'suspended');


CREATE TABLE IF NOT EXISTS members (
  id                    UUID DEFAULT uuid_generate_v4(),
  member_site_id        UUID NOT NULL,
  member_class_id       UUID NOT NULL,
  member_level_id       UUID NOT NULL,
  username              TEXT NOT NULL,
  password              TEXT NOT NULL,
  nickname              TEXT NOT NULL,
  mobile_phone_number   TEXT,
  state                 MEMBER_STATE DEFAULT 'normal',
  state_changed_at      BIGINT,
  last_signined_ip      TEXT,
  last_signined_at      BIGINT,
  referrer_member_id    UUID,
  referred_count        BIGINT NOT NULL,
  created_at            BIGINT NOT NULL DEFAULT (extract(epoch from now()) * 1000),
  updated_at            BIGINT NOT NULL DEFAULT (extract(epoch from now()) * 1000),
  deleted_at            BIGINT,
  PRIMARY KEY (id),
  UNIQUE (username),
  CONSTRAINT fk_members_member_site_id
    FOREIGN KEY(member_site_id) 
	    REFERENCES member_sites(id),
  CONSTRAINT fk_members_member_class_id
    FOREIGN KEY(member_class_id) 
	    REFERENCES member_classes(id),
  CONSTRAINT fk_members_member_level_id
    FOREIGN KEY(member_level_id) 
	    REFERENCES member_levels(id),
  CONSTRAINT fk_members_referrer_member_id
    FOREIGN KEY(referrer_member_id) 
	    REFERENCES members(id)
      
);

CREATE INDEX idx_members_username ON members (username);

-- trigger (updated_at)
CREATE TRIGGER tg_members_updated_at
  BEFORE UPDATE
  ON members
  FOR EACH ROW
  EXECUTE PROCEDURE update_updated_at_column();

-- trigger (state_changed_at)
CREATE TRIGGER tg_members_state_changed_at
  BEFORE UPDATE
  ON members
  FOR EACH ROW
  EXECUTE PROCEDURE update_state_changed_at_column();
