# Krow Mobile Staff App - Architecture Document

## A. Introduction

This document outlines the architecture of the Krow Mobile Staff App, a Flutter application designed to connect staff with job opportunities. The app provides features for staff to manage their profiles, view and apply for shifts, track earnings, and complete necessary paperwork.

The core purpose of the app is to streamline the process of finding and managing temporary work, providing a seamless experience for staff from onboarding to payment.

## B. Full Architecture Overview

The application follows a **Clean Architecture** pattern, separating concerns into three main layers: **Presentation**, **Domain**, and **Data**. This layered approach promotes a separation of concerns, making the codebase more maintainable, scalable, and testable.

-   **Presentation Layer:** This layer is responsible for the UI and user interaction. It consists of widgets, screens, and Blocs that manage the UI state. The Presentation Layer depends on the Domain Layer to execute business logic.

-   **Domain Layer:** This layer contains the core business logic of the application. It consists of use cases (interactors), entities (business objects), and repository interfaces. The Domain Layer is independent of the other layers.

-   **Data Layer:** This layer is responsible for data retrieval and storage. It consists of repository implementations, data sources (API clients, local database), and data transfer objects (DTOs). The Data Layer depends on the Domain Layer and implements the repository interfaces defined in it.

### Integration Points

-   **UI → Domain:** The UI (e.g., a button press) triggers a method in a Bloc. The Bloc then calls a use case in the Domain Layer to execute the business logic.
-   **Domain → Data:** The use case calls a method on a repository interface.
-   **Data → External:** The repository implementation, located in the Data Layer, communicates with external data sources (GraphQL API, Firebase, local storage) to retrieve or store data.

## C. Backend Architecture

The backend is built on a combination of a **GraphQL server** and **Firebase services**.

-   **GraphQL Server:** The primary endpoint for the Flutter app. It handles most of the business logic and data aggregation. The server is responsible for communicating with Firebase services to fulfill requests.

-   **Firebase Services:**
    -   **Firebase Auth:** Used for user authentication, primarily with phone number verification.
    -   **Firebase Firestore:** The main database for storing application data, such as user profiles, shifts, and earnings.
    -   **Firebase Storage:** Used for storing user-generated content, such as profile avatars.
    -   **Firebase Cloud Messaging:** Used for sending push notifications to users.
    -   **Firebase Remote Config:** Used for remotely configuring app parameters.

### API Flow

1.  **Flutter App to GraphQL:** The Flutter app sends GraphQL queries and mutations to the GraphQL server.
2.  **GraphQL to Firebase:** The GraphQL server resolves these operations by interacting with Firebase services. For example, a `getShifts` query will fetch data from Firestore, and an `updateStaffPersonalInfoWithAvatar` mutation will update a document in Firestore and upload a file to Firebase Storage.
3.  **Response Flow:** The data flows back from Firebase to the GraphQL server, which then sends it back to the Flutter app.

## D. API Layer

The API layer is responsible for all communication with the backend.

-   **GraphQL Operations:** The app uses the `graphql_flutter` package to interact with the GraphQL server. Queries, mutations, and subscriptions are defined in `.dart` files within each feature's `data` directory.

-   **API Error Handling:** The `ApiClient` class is responsible for handling API errors. It catches exceptions and returns a `Failure` object, which is then handled by the Bloc in the Presentation Layer to show an appropriate error message to the user.

-   **Caching:** The `graphql_flutter` client provides caching capabilities. The app uses a `HiveStore` to cache GraphQL responses, reducing the number of network requests and improving performance.

-   **Parsing:** JSON responses from the API are parsed into Dart objects using the `json_serializable` package.

## E. State Management

The application uses the **Bloc** library for state management.

-   **Why Bloc?** Bloc is a predictable state management library that helps to separate business logic from the UI. It enforces a unidirectional data flow, making the app's state changes predictable and easier to debug.

-   **State Flow:**
    1.  **UI Event:** The UI dispatches an event to the Bloc.
    2.  **Bloc Logic:** The Bloc receives the event, executes the necessary business logic (often by calling a use case), and emits a new state.
    3.  **UI Update:** The UI listens to the Bloc's state changes and rebuilds itself to reflect the new state.

-   **Integration with API Layer:** Blocs interact with the API layer through use cases. When a Bloc needs to fetch data from the backend, it calls a use case, which in turn calls a repository that communicates with the API.

## F. Use-Case Flows

### User Authentication

1.  **UI:** The user enters their phone number.
2.  **Logic:** The `AuthBloc` sends the phone number to Firebase Auth for verification.
3.  **Backend:** Firebase Auth sends a verification code to the user's phone.
4.  **UI:** The user enters the verification code.
5.  **Logic:** The `AuthBloc` verifies the code with Firebase Auth.
6.  **Backend:** Firebase Auth returns an auth token.
7.  **Logic:** The app sends the auth token to the GraphQL server to get the user's profile.
8.  **Response:** The GraphQL server returns the user's data, and the app navigates to the home screen.

### Shift Management

1.  **UI:** The user navigates to the shifts screen.
2.  **Logic:** The `ShiftsBloc` requests a list of shifts.
3.  **Backend:** The use case calls the `ShiftsRepository`, which sends a `getShifts` query to the GraphQL server. The server fetches the shifts from Firestore.
4.  **Response:** The GraphQL server returns the list of shifts, which is then displayed on the UI.

## G. Replacing or Plugging in a New Backend: Considerations & Recommendations

This section provides guidance on how to replace the current GraphQL + Firebase backend with a different solution (e.g., REST, Supabase, Hasura).

### Tightly Coupled Components

-   **Data Layer:** The current `ApiProvider` implementations are tightly coupled to the GraphQL API.
-   **Authentication:** The authentication flow is tightly coupled to Firebase Auth.
-   **DTOs:** The data transfer objects are generated based on the GraphQL schema.

### Abstraction Recommendations

To make the architecture more backend-agnostic, the following components should be abstracted:

-   **Repositories:** The repository interfaces in the Domain Layer should remain unchanged. The implementations in the Data Layer will need to be rewritten for the new backend.
-   **Services:** Services like authentication should be abstracted behind an interface. For example, an `AuthService` interface can be defined in the Domain Layer, with a `FirebaseAuthService` implementation in the Data Layer.
-   **DTOs:** The DTOs should be mapped to domain entities in the Data Layer. This ensures that the Domain Layer is not affected by changes in the backend's data model.
-   **Error Handling:** A generic error handling mechanism should be implemented to handle different types of backend errors.

### Suggested Design Improvements

-   **Introduce a Service Locator:** Use a service locator like `get_it` to decouple the layers and make it easier to swap out implementations.
-   **Define Abstract Data Sources:** Instead of directly calling the API client in the repository implementations, introduce abstract data source interfaces (e.g., `UserRemoteDataSource`). This adds another layer of abstraction and makes the repositories more testable.

### Migration Strategies

1.  **Define Interfaces:** Start by defining abstract interfaces for all backend interactions (repositories, services).
2.  **Implement New Data Layer:** Create a new implementation of the Data Layer for the new backend. This will involve writing new repository implementations, API clients, and DTOs.
3.  **Swap Implementations:** Use the service locator to swap the old Data Layer implementation with the new one.
4.  **Test:** Thoroughly test the application to ensure that everything works as expected with the new backend.

By following these recommendations, the Krow Mobile Staff App can be migrated to a new backend with minimal impact on the overall architecture and business logic.
