#!/bin/bash
#==============================================================================
# pre-commit hook (Monorepo: frontend + backend)
# TypeScript 컴파일 + 린트 검증 — 실패 시 커밋 차단
#==============================================================================

REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)

# npm 확인
if ! command -v npx &>/dev/null; then
    echo "경고: npx가 설치되지 않았습니다. 검증을 건너뜁니다."
    exit 0
fi

FAILED=0

#--- Frontend ---
if [ -d "$REPO_ROOT/frontend/node_modules" ]; then
    echo "pre-commit: [frontend] TypeScript 타입 체크 중..."
    (cd "$REPO_ROOT/frontend" && npx tsc --noEmit --pretty 2>&1)
    if [ $? -ne 0 ]; then
        echo ""
        echo "╔══════════════════════════════════════════════════════════╗"
        echo "║  [frontend] TypeScript 타입 에러! 커밋이 차단됩니다.    ║"
        echo "╚══════════════════════════════════════════════════════════╝"
        FAILED=1
    else
        echo "pre-commit: [frontend] 타입 체크 성공"
    fi

    # ESLint 검증 (설정 파일이 있는 경우만)
    if [ -f "$REPO_ROOT/frontend/eslint.config.js" ] || [ -f "$REPO_ROOT/frontend/eslint.config.mjs" ] || \
       [ -f "$REPO_ROOT/frontend/.eslintrc.js" ] || [ -f "$REPO_ROOT/frontend/.eslintrc.json" ] || [ -f "$REPO_ROOT/frontend/.eslintrc.cjs" ]; then
        echo "pre-commit: [frontend] ESLint 검증 중..."
        (cd "$REPO_ROOT/frontend" && npx eslint src/ --ext .ts,.tsx --quiet 2>&1)
        if [ $? -ne 0 ]; then
            echo ""
            echo "╔══════════════════════════════════════════════════════════╗"
            echo "║  [frontend] ESLint 에러! 커밋이 차단됩니다.            ║"
            echo "╚══════════════════════════════════════════════════════════╝"
            FAILED=1
        else
            echo "pre-commit: [frontend] ESLint 통과"
        fi
    fi
else
    echo "pre-commit: [frontend] node_modules 없음, 건너뜁니다."
fi

#--- Backend ---
if [ -d "$REPO_ROOT/backend/node_modules" ]; then
    echo "pre-commit: [backend] TypeScript 타입 체크 중..."
    (cd "$REPO_ROOT/backend" && npx tsc --noEmit --pretty 2>&1)
    if [ $? -ne 0 ]; then
        echo ""
        echo "╔══════════════════════════════════════════════════════════╗"
        echo "║  [backend] TypeScript 타입 에러! 커밋이 차단됩니다.     ║"
        echo "╚══════════════════════════════════════════════════════════╝"
        FAILED=1
    else
        echo "pre-commit: [backend] 타입 체크 성공"
    fi
else
    echo "pre-commit: [backend] node_modules 없음, 건너뜁니다."
fi

if [ $FAILED -ne 0 ]; then
    echo ""
    echo "타입/린트 에러를 수정한 후 다시 커밋해주세요."
    exit 1
fi
