--- client-details

CREATE TABLE client_details (
  client_id      BIGINT PRIMARY KEY REFERENCES clients (id),

  first_name     VARCHAR(1024),
  middle_name    VARCHAR(1024),
  last_name      VARCHAR(1024),

  sex            VARCHAR(255),
  birthday       VARCHAR(255),
  cellphone      VARCHAR(255),
  email          VARCHAR(255),

  ext_ref        VARCHAR(1024),
  card_ref       VARCHAR(1024),

  branch_id      VARCHAR(1024),
  branch_name    VARCHAR(1024),
  branch_ext_ref VARCHAR(1024),
  branch_bik     VARCHAR(1024),

  created_at     TIMESTAMPTZ NOT NULL,
  updated_at     TIMESTAMPTZ NOT NULL
);

-- Migrate existing clients.

INSERT INTO client_details (
  client_id,

  first_name,
  middle_name,
  last_name,

  sex,
  birthday,
  cellphone,
  email,

  ext_ref,
  card_ref,

  branch_id,
  branch_name,
  branch_ext_ref,
  branch_bik,

  created_at,
  updated_at
) (
  SELECT
    clients.id,

    c.first_name,
    c.middle_name,
    c.last_name,
    c.sex,
    c.birthday,
    c.cellphone,
    c.email,

    c.ext_ref,
    c.card_ref,

    c.branch_id,
    c.branch_name,
    c.branch_ext_ref,
    c.branch_bik,

    c.created_at,
    c.updated_at
  FROM clients
    JOIN crm_customers c ON c.id = clients.customer_id
);
