-- 소모품 구매 관리 시스템 v2: 상태 확장 + 그룹화 + 별칭 + 입고

-- 1. purchase_requests.status ENUM 확장
ALTER TABLE purchase_requests
  MODIFY COLUMN status ENUM('pending','grouped','purchased','received','hold') DEFAULT 'pending'
  COMMENT '대기, 구매진행중, 구매완료, 입고완료, 보류';

-- 2. 입고/그룹 관련 컬럼 추가
ALTER TABLE purchase_requests
  ADD COLUMN batch_id INT NULL COMMENT '구매 묶음 ID' AFTER photo_path,
  ADD COLUMN received_photo_path VARCHAR(255) NULL COMMENT '입고 사진' AFTER batch_id,
  ADD COLUMN received_location VARCHAR(200) NULL COMMENT '입고 보관 위치' AFTER received_photo_path,
  ADD COLUMN received_at TIMESTAMP NULL COMMENT '입고 확인 시각' AFTER received_location,
  ADD COLUMN received_by INT NULL COMMENT '입고 확인자' AFTER received_at,
  ADD CONSTRAINT fk_pr_received_by FOREIGN KEY (received_by) REFERENCES sso_users(user_id);

-- 3. 구매 묶음(그룹) 테이블
CREATE TABLE IF NOT EXISTS purchase_batches (
  batch_id INT AUTO_INCREMENT PRIMARY KEY,
  batch_name VARCHAR(100) COMMENT '묶음 이름',
  category ENUM('consumable','safety','repair','equipment') NULL COMMENT '분류',
  vendor_id INT NULL COMMENT '예정 업체',
  status ENUM('pending','purchased','received') DEFAULT 'pending'
    COMMENT '진행중, 구매완료, 입고완료',
  notes TEXT,
  created_by INT NOT NULL COMMENT '생성자',
  purchased_at TIMESTAMP NULL COMMENT '구매 처리 시점',
  purchased_by INT NULL COMMENT '구매 처리자',
  received_at TIMESTAMP NULL COMMENT '입고 확인 시점',
  received_by INT NULL COMMENT '입고 확인자',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (vendor_id) REFERENCES vendors(vendor_id),
  FOREIGN KEY (created_by) REFERENCES sso_users(user_id),
  FOREIGN KEY (purchased_by) REFERENCES sso_users(user_id),
  FOREIGN KEY (received_by) REFERENCES sso_users(user_id)
);

-- 4. batch FK
ALTER TABLE purchase_requests
  ADD CONSTRAINT fk_pr_batch FOREIGN KEY (batch_id)
  REFERENCES purchase_batches(batch_id) ON DELETE SET NULL;

-- 5. 품목 별칭 테이블 (한국어 동의어/약어 매핑)
CREATE TABLE IF NOT EXISTS item_aliases (
  alias_id INT AUTO_INCREMENT PRIMARY KEY,
  item_id INT NOT NULL COMMENT 'FK → consumable_items',
  alias_name VARCHAR(100) NOT NULL COMMENT '별칭/축약어',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (item_id) REFERENCES consumable_items(item_id) ON DELETE CASCADE,
  UNIQUE KEY uq_item_alias (item_id, alias_name),
  INDEX idx_alias_name (alias_name)
);

-- 6. notification_recipients ENUM에 'purchase' 추가
ALTER TABLE notification_recipients
  MODIFY COLUMN notification_type
  ENUM('repair','safety','nonconformity','equipment','maintenance','system','purchase')
  NOT NULL COMMENT '알림 유형';

-- 7. 페이지 키 등록
INSERT IGNORE INTO pages (page_key, page_name, page_path, category, is_admin_only, display_order) VALUES
('purchase.request_mobile', '소모품 신청 (모바일)', '/pages/purchase/request-mobile.html', 'purchase', 0, 42);
