-- =====================================================================
-- expense_db 마이그레이션 #002 — 결재 워크플로 + 첨부파일
-- =====================================================================
-- 실행:
--   docker exec -i postgres-db psql -U postgres -d expense_db \
--       < scripts/sql/expense_db_002_workflow_attachments.sql
--
-- 멱등. init.sql 도 동일 변경을 포함하므로 신규 설치는 init 하나로 충분.
-- 이미 운영 중인 DB 에만 별도로 적용한다.
-- =====================================================================

\set ON_ERROR_STOP on

-- expense_items 컬럼 추가
ALTER TABLE expense_items
  ADD COLUMN IF NOT EXISTS approver_email TEXT,
  ADD COLUMN IF NOT EXISTS decided_at     TIMESTAMPTZ,
  ADD COLUMN IF NOT EXISTS reject_reason  TEXT;

-- 첨부파일 테이블
CREATE TABLE IF NOT EXISTS expense_attachments (
    id            TEXT        PRIMARY KEY,
    item_id       TEXT        NOT NULL REFERENCES expense_items(id) ON DELETE CASCADE,
    owner         TEXT        NOT NULL,
    kind          TEXT        NOT NULL CHECK (kind IN ('receipt', 'other')),
    filename      TEXT        NOT NULL,
    stored_path   TEXT        NOT NULL,
    content_type  TEXT        NOT NULL DEFAULT 'application/octet-stream',
    size_bytes    BIGINT      NOT NULL DEFAULT 0 CHECK (size_bytes >= 0),
    uploaded_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_attach_item ON expense_attachments (item_id);

GRANT SELECT, INSERT, UPDATE, DELETE ON expense_attachments TO expense_app;

SELECT 'migration 002 applied' AS status;
