# 🔥 시험족보 서비스 - Firebase 설정 가이드

## 1단계: Firebase 프로젝트 생성

1. [console.firebase.google.com](https://console.firebase.google.com) 접속
2. **"프로젝트 추가"** 클릭
3. 프로젝트 이름 입력 (예: `jokbo-app`)
4. Google Analytics 선택 후 생성

---

## 2단계: 웹 앱 등록 및 SDK 설정

1. 프로젝트 대시보드 → **⚙️ 설정 > 일반** → 하단 "내 앱" → **웹 앱 추가(</> 아이콘)**
2. 앱 닉네임 입력 후 등록
3. `firebaseConfig` 객체 복사

**index.html 상단 이 부분을 교체:**
```javascript
const firebaseConfig = {
  apiKey: "AIzaSy...",           // ← 실제 값으로 교체
  authDomain: "jokbo-app.firebaseapp.com",
  projectId: "jokbo-app",
  storageBucket: "jokbo-app.appspot.com",
  messagingSenderId: "123456789",
  appId: "1:123456789:web:abc123"
};
```

---

## 3단계: Firestore Database 활성화

1. 좌측 메뉴 **Firestore Database** → **데이터베이스 만들기**
2. **프로덕션 모드** 선택 (보안 규칙은 아래 참조)
3. 리전: `asia-northeast3 (Seoul)` 선택

**firestore.rules 파일을 Firebase 콘솔에 적용:**
```
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // 족보 게시물
    match /posts/{postId} {
      allow read: if true;
      allow create: if request.auth != null && request.resource.data.authorId == request.auth.uid;
      allow update: if request.auth != null && (
        resource.data.authorId == request.auth.uid ||
        // 좋아요, 조회수, 다운로드수 업데이트는 누구나
        request.resource.data.diff(resource.data).affectedKeys().hasOnly(['likes','views','downloads'])
      );
      allow delete: if request.auth != null && resource.data.authorId == request.auth.uid;
      
      // 댓글
      match /comments/{commentId} {
        allow read: if true;
        allow create: if request.auth != null;
        allow delete: if request.auth != null && resource.data.authorId == request.auth.uid;
      }
    }
    
    // 사용자 프로필
    match /users/{userId} {
      allow read: if true;
      allow create, update: if request.auth != null;
    }
  }
}
```

---

## 4단계: Authentication 활성화

1. 좌측 메뉴 **Authentication** → **시작하기**
2. **이메일/비밀번호** → 사용 설정 ON
3. **Google** → 사용 설정 ON → 프로젝트 지원 이메일 입력 → 저장

---

## 5단계: Storage 활성화

1. 좌측 메뉴 **Storage** → **시작하기**
2. 프로덕션 모드 선택, 리전 `asia-northeast3` 선택

**storage.rules:**
```
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /jokbo/{allPaths=**} {
      allow read: if true;
      allow write: if request.auth != null
                   && request.resource.size < 10 * 1024 * 1024  // 10MB
                   && request.resource.contentType.matches('application/pdf|image/.*|application/.*word.*|application/haansofthwp');
    }
  }
}
```

---

## 6단계: Firestore 인덱스 설정

Firestore 콘솔 → **인덱스** → **복합 인덱스 추가:**

| 컬렉션 | 필드1 | 필드2 | 쿼리 범위 |
|--------|-------|-------|----------|
| posts  | type (오름차순) | createdAt (내림차순) | 컬렉션 |
| posts  | type (오름차순) | likes (내림차순) | 컬렉션 |
| posts  | type (오름차순) | views (내림차순) | 컬렉션 |
| posts  | year (오름차순) | createdAt (내림차순) | 컬렉션 |

---

## 7단계: Google Search Console (SEO) 설정

1. [search.google.com/search-console](https://search.google.com/search-console) 접속
2. 속성 추가 → 도메인 또는 URL 접두어 입력
3. HTML 메타 태그 인증 방법 선택 → 태그를 index.html `<head>`에 추가:
   ```html
   <meta name="google-site-verification" content="YOUR_CODE" />
   ```
4. **sitemap.xml** 제출 (아래 파일 참조)

---

## 8단계: Firebase Hosting으로 배포 (무료)

```bash
# Firebase CLI 설치
npm install -g firebase-tools

# 로그인
firebase login

# 프로젝트 초기화
firebase init hosting

# 배포
firebase deploy --only hosting
```

firebase.json 설정:
```json
{
  "hosting": {
    "public": ".",
    "ignore": ["firebase.json", "*.rules", "*.md"],
    "rewrites": [{ "source": "**", "destination": "/index.html" }],
    "headers": [
      {
        "source": "**",
        "headers": [
          { "key": "X-Content-Type-Options", "value": "nosniff" },
          { "key": "X-Frame-Options", "value": "DENY" },
          { "key": "Cache-Control", "value": "public, max-age=3600" }
        ]
      }
    ]
  }
}
```

---

## 무료 플랜(Spark) 한도

| 서비스 | 무료 한도 |
|--------|----------|
| Firestore 읽기 | 50,000회/일 |
| Firestore 쓰기 | 20,000회/일 |
| Storage | 5GB |
| Hosting | 10GB/월 전송 |
| Authentication | 무제한 |

> 💡 월 방문자 약 5,000~10,000명 수준까지 무료로 운영 가능합니다.

---

## SEO 추가 최적화 체크리스트

- [ ] Google Search Console 속성 등록
- [ ] sitemap.xml 제출
- [ ] robots.txt 설정
- [ ] 사이트 로딩속도 최적화 (PageSpeed Insights)
- [ ] 학교별 랜딩 페이지 생성 (예: `/seoul-univ`, `/yonsei`)
- [ ] 과목별 메타 태그 동적 생성
