-- Admin şifre sıfırlama: e-posta + tek kullanımlık kod (SMTP panelden / .env)
-- Bir kez çalıştırın.

USE faunamix;

SET @has_email := (
  SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'admin_users' AND COLUMN_NAME = 'email'
);
SET @sql_email := IF(@has_email = 0,
  'ALTER TABLE admin_users ADD COLUMN email VARCHAR(255) NULL AFTER username',
  'SELECT 1');
PREPARE stmt FROM @sql_email; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @has_uq_email := (
  SELECT COUNT(*) FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'admin_users' AND INDEX_NAME = 'uq_admin_users_email'
);
SET @sql_uq_email := IF(@has_uq_email = 0,
  'ALTER TABLE admin_users ADD UNIQUE KEY uq_admin_users_email (email)',
  'SELECT 1');
PREPARE stmt FROM @sql_uq_email; EXECUTE stmt; DEALLOCATE PREPARE stmt;

CREATE TABLE IF NOT EXISTS admin_password_resets (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  admin_user_id INT UNSIGNED NOT NULL,
  code_hash VARCHAR(255) NOT NULL,
  expires_at DATETIME NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_admin_pwd_reset_user (admin_user_id),
  KEY idx_admin_pwd_reset_expires (expires_at),
  CONSTRAINT fk_admin_pwd_reset_user FOREIGN KEY (admin_user_id) REFERENCES admin_users (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

UPDATE admin_users
SET email = 'admin@example.invalid'
WHERE username = 'admin' AND (email IS NULL OR email = '');
