-- 01_99_dms_data_v5_1_deploy_table_password_resets.sql
-- Purpose: Table for password reset flow (forgot/reset password)
-- Depends on: users

SET NAMES utf8mb4;
SET time_zone = '+00:00';
SET FOREIGN_KEY_CHECKS=0;
-- ใช้ IF NOT EXISTS ป้องกันรันซ้ำ
CREATE TABLE IF NOT EXISTS password_resets (
  id           BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  user_id      BIGINT UNSIGNED NOT NULL,
  token_hash   CHAR(64)        NOT NULL COMMENT 'SHA-256(hex) ของ token ดิบที่ส่งให้ผู้ใช้',
  expires_at   DATETIME        NOT NULL,
  used_at      DATETIME        NULL,
  created_at   DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_password_resets_token_hash (token_hash),
  KEY idx_password_resets_user_id   (user_id),
  KEY idx_password_resets_expires   (expires_at),
  CONSTRAINT fk_password_resets_user
    FOREIGN KEY (user_id) REFERENCES users(user_id)
    ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
SET FOREIGN_KEY_CHECKS=1;
-- (ออปชัน) กำจัด token ที่หมดอายุอัตโนมัติด้วย EVENT (หากเปิด event_scheduler)
-- CREATE EVENT IF NOT EXISTS ev_prune_password_resets
--   ON SCHEDULE EVERY 1 DAY
--   DO DELETE FROM password_resets WHERE (used_at IS NOT NULL) OR (expires_at < NOW());

-- DOWN (rollback)
-- DROP TABLE IF EXISTS password_resets;
