# Specification: Technical Integrity Standardization Suite

## 1. Overview
This track implements a comprehensive suite of architectural standardizations to reduce boilerplate, enforce security, and ensure a "Single Source of Truth" across the Jomblo codebase. We will transition from manual, repetitive patterns to centralized, type-safe, and highly-automated wrappers and helpers.

## 2. Functional Requirements

### 2.1 Guarded Action Wrapper (`createServerAction`)
- **Centralized Logic:** Create a higher-order function to wrap server action handlers.
- **Automated Checks:** 
    - Session authentication and role-based access control (RBAC).
    - Input validation via Zod schemas.
    - Rate limiting (integrated with existing Redis-based limiter).
- **Traceability:** Automatically wrap execution in `LoggerContext.withLogging`.
- **Error Mapping:** Convert thrown `AppError` instances (and unexpected errors) into a standardized `ActionResponse`.

### 2.2 Data Access Layer (Repository Pattern)
- **Centralized SQL:** Move raw SQL queries from server actions to a dedicated `lib/db/repositories/` directory.
- **Initial Target:** Implement `CatalogRepository` for product, category, and brand operations.
- **API Consistency:** Repository methods should return clean data or throw standard error classes.

### 2.3 `useAction` Frontend Hook
- **State Management:** Manage `loading`, `data`, `error`, and `validationErrors`.
- **Automated Feedback:** Optional configuration to trigger `sonner` toasts on success or failure.
- **Simplification:** Provide an `execute` function for forms and triggers.

### 2.4 Zod-Driven Type Synchronization
- **Eliminate Type Drift:** Infer TypeScript types directly from Zod schemas using `z.infer`.
- **Cleanup:** Remove redundant manual interfaces in `types/` that duplicate schema definitions.

### 2.5 Unified Application Error Classes
- **Hierarchy:** Define `AppError`, `UnauthorizedError`, `RateLimitError`, `NotFoundError`, and `ValidationError`.
- **Workflow:** Throw these classes within business logic; the `createServerAction` wrapper handles mapping to the public `ActionResponse`.

### 2.6 Environment Variable Validator
- **Safe Initialization:** Create `lib/env.ts` using Zod to parse and validate `process.env` at startup.
- **Fail-Fast:** Prevent application startup if critical variables (e.g., `DATABASE_URL`, `STRIPE_SECRET_KEY`) are missing or invalid.

## 3. Pilot Implementation: Catalog Module
- **Action Migration:** Refactor `actions/catalog.ts` to use `createServerAction`.
- **Repository Migration:** Move Catalog-related SQL to `lib/db/repositories/catalog.repository.ts`.
- **UI Migration:** Update a Catalog-related component (e.g., Product Form or Category Manager) to use `useAction`.

## 4. Acceptance Criteria
- [ ] `lib/env.ts` successfully validates all required environment variables.
- [ ] `CatalogRepository` centralizes all Catalog SQL; no raw SQL remains in `actions/catalog.ts`.
- [ ] `createServerAction` successfully validates input, checks auth, and maps errors for Catalog actions.
- [ ] All Catalog types are inferred from Zod schemas.
- [ ] `useAction` hook simplifies Catalog-related frontend components.
- [ ] Automated tests (Vitest) confirm that the refactored Catalog actions behave identically to the original ones.
- [ ] **100% Test Coverage:** All new/modified files must have 100% test coverage.
- [ ] **Documentation:** Update architectural docs (`GEMINI.md`, `docs/ARCHITECTURE.md`) after implementation.

## 5. Out of Scope
- Migrating all server actions in the entire project (only the Catalog pilot is included in this track).
- Major changes to the underlying database schema.