-- DevX RP v0.4.1 migration. Resources also create these structures at runtime.
SET @has_contact_type := (
  SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'devx_phone_contacts' AND COLUMN_NAME = 'contact_type'
);
SET @sql_contact_type := IF(@has_contact_type = 0,
  "ALTER TABLE devx_phone_contacts ADD COLUMN contact_type VARCHAR(32) NOT NULL DEFAULT 'player' AFTER phone_number",
  'SELECT 1');
PREPARE stmt_contact_type FROM @sql_contact_type; EXECUTE stmt_contact_type; DEALLOCATE PREPARE stmt_contact_type;

SET @has_metadata := (
  SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'devx_phone_contacts' AND COLUMN_NAME = 'metadata'
);
SET @sql_metadata := IF(@has_metadata = 0,
  'ALTER TABLE devx_phone_contacts ADD COLUMN metadata LONGTEXT NULL AFTER contact_type',
  'SELECT 1');
PREPARE stmt_metadata FROM @sql_metadata; EXECUTE stmt_metadata; DEALLOCATE PREPARE stmt_metadata;

CREATE TABLE IF NOT EXISTS devx_casino_wallets (
  character_id BIGINT UNSIGNED NOT NULL,
  chips BIGINT UNSIGNED NOT NULL DEFAULT 0,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (character_id),
  CONSTRAINT fk_devx_casino_wallet_character FOREIGN KEY (character_id)
    REFERENCES devx_characters (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS devx_club_relations (
  character_id BIGINT UNSIGNED NOT NULL,
  relation_key VARCHAR(32) NOT NULL,
  satisfaction TINYINT UNSIGNED NOT NULL DEFAULT 0,
  contact_unlocked TINYINT(1) NOT NULL DEFAULT 0,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (character_id, relation_key),
  CONSTRAINT fk_devx_club_character FOREIGN KEY (character_id)
    REFERENCES devx_characters (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
