# Manual Integration Guide: Google Sign-In with Firebase Auth

This document provides step-by-step instructions on how to transition from the simulated Google login to a production-ready Google Authentication system using Firebase Auth in the React frontend.

---

## Step 1: Firebase Project Setup

1. Go to the [Firebase Console](https://console.firebase.google.com/).
2. Click **Add Project** and follow the prompts to create a new project.
3. Once the project is created, click the **Web icon** (`</>`) on the project overview page to register a new web application.
4. Copy the `firebaseConfig` details provided in the Firebase Console. It will look like this:
   ```javascript
   const firebaseConfig = {
     apiKey: "YOUR_API_KEY",
     authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
     projectId: "YOUR_PROJECT_ID",
     storageBucket: "YOUR_PROJECT_ID.firebasestorage.app",
     messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
     appId: "YOUR_APP_ID"
   };
   ```

---

## Step 2: Enable Google Authentication

1. In the left-hand navigation sidebar of the Firebase Console, go to **Build** > **Authentication**.
2. Click **Get Started** if this is the first time setting up Authentication.
3. Navigate to the **Sign-in method** tab.
4. Click **Add new provider** and select **Google**.
5. Enable the toggle, configure your public-facing project name, select a project support email, and click **Save**.
6. (Optional) Under **Authorized domains**, ensure `localhost` and your production domain are listed so OAuth redirects work.

---

## Step 3: Set Up Project Credentials in Google Cloud Console

Google Sign-in requires OAuth consent. If you see redirect issues:
1. Go to the [Google Cloud Console](https://console.cloud.google.com/).
2. Select your Firebase project from the dropdown.
3. Go to **APIs & Services** > **OAuth consent screen**.
4. Configure the publishing status to **Testing** or **Production**, add test users if in Testing, and fill out required app details.

---

## Step 4: Frontend Code Integration

### 1. Install Firebase SDK
Ensure firebase dependencies are installed in your frontend folder:
```bash
npm install firebase
```

### 2. Configure Firebase Auth Client
Create/update `frontend/src/lib/firebaseConfig.ts` with the copied configurations:
```typescript
import { initializeApp } from 'firebase/app';
import { getAuth, GoogleAuthProvider } from 'firebase/auth';

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_PROJECT_ID.firebasestorage.app",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

// Initialize Firebase Auth
export const auth = getAuth(app);
export const googleProvider = new GoogleAuthProvider();
```

### 3. Implement Sign-in Action
In `LoginPage.tsx`, replace the mock handlers with real Firebase Auth sign-in triggers:
```typescript
import { signInWithPopup } from 'firebase/auth';
import { auth, googleProvider } from '../lib/firebaseConfig';

const handleGoogleSignIn = async () => {
  try {
    const result = await signInWithPopup(auth, googleProvider);
    const user = result.user;
    const email = user.email; // e.g. student.240007@cse.ritchennai.edu.in
    const displayName = user.displayName || "RIT User";

    // Call your backend/database lookup or sync user details
    const response = await fetch(API_BASE_URL + '/api/auth/google-login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, fullName: displayName })
    });

    if (response.ok) {
      const userData = await response.json();
      login(userData);
    } else {
      const errorData = await response.json();
      alert(errorData.message || "Failed to log in.");
    }
  } catch (error) {
    console.error("Google Sign-In Error:", error);
  }
};
```

---

## Step 5: Backend Integration (Spring Boot)

To support Google authentication token validation or syncing, add a secure endpoint:
```java
@PostMapping("/api/auth/google-login")
public ResponseEntity<?> googleLogin(@RequestBody Map<String, String> payload) {
    String email = payload.get("email");
    String fullName = payload.get("fullName");

    if (email == null || email.trim().isEmpty()) {
        return ResponseEntity.badRequest().body(Map.of("message", "Email is required"));
    }

    email = email.trim().toLowerCase();
    
    // Check if user already exists
    Optional<User> existingUser = userRepository.findByEmail(email);
    if (existingUser.isPresent()) {
        return ResponseEntity.ok(existingUser.get());
    }

    // Auto-register RIT student if email matches the student format
    if (email.matches("^student\\.\\d{6}@[a-zA-Z0-9&-_]+\\.ritchennai\\.edu\\.in$")) {
        User newStudent = new User();
        newStudent.setEmail(email);
        newStudent.setFullName(fullName);
        newStudent.setRole("STUDENT");
        
        // Parse department & batch logic here
        String rollNumber = email.split("@")[0].substring(8); // extracts roll e.g. "240007"
        String rawDept = email.split("@")[1].split("\\.")[0]; // cse
        
        newStudent.setRegNo(rollNumber);
        
        // Set Department
        newStudent.setDepartment(mapDepartmentDomain(rawDept));
        
        // Set Year Batch
        int joinYear = 2000 + Integer.parseInt(rollNumber.substring(0, 2));
        int currentYear = LocalDate.now().getYear();
        int academicOffset = LocalDate.now().getMonthValue() >= 6 ? 1 : 0;
        int yearIndex = currentYear - joinYear + academicOffset;
        String[] years = {"1st Year", "2nd Year", "3rd Year", "4th Year"};
        newStudent.setInchargeBatch(yearIndex >= 1 && yearIndex <= 4 ? years[yearIndex - 1] : "N/A");
        newStudent.setInchargeClass(newStudent.getDepartment());
        newStudent.setInchargeSection("A");
        
        // Generate random placeholder password for DB constraints
        newStudent.setPassword(passwordEncoder.encode(UUID.randomUUID().toString()));
        
        userRepository.save(newStudent);
        return ResponseEntity.ok(newStudent);
    }

    return ResponseEntity.status(401).body(Map.of("message", "Access denied. Only registered accounts can log in."));
}
```
