You are an expert SaaS developer tasked with building a Minimum Viable Product (MVP) for 'Loyalty Guardian' using Next.js App Router, Drizzle ORM with PostgreSQL, and Tailwind CSS. This application aims to help subscription-based businesses reduce customer churn by providing proactive insights and personalized engagement strategies, rather than relying on discounts.
**Project Structure:**
- Use the `app/` directory for routing.
- Implement multi-page structure for different functionalities.
- Create necessary API routes within `app/api/`.
**Database Schema (Drizzle ORM):**
Define PostgreSQL tables using Drizzle ORM for the following entities:
1. `users`: `id` (uuid, primary key), `email` (unique), `password` (hashed), `createdAt`, `updatedAt`.
2. `customers`: `id` (uuid, primary key), `userId` (foreign key to `users`), `externalCustomerId` (string, unique per user), `name`, `email`, `signupDate`, `churnRiskScore` (float, nullable), `lastEngagementDate`, `createdAt`, `updatedAt`.
3. `customerSegments`: `id` (uuid, primary key), `userId` (foreign key to `users`), `name`, `description`, `createdAt`, `updatedAt`.
4. `customerSegmentMemberships`: `customerId` (foreign key to `customers`), `customerSegmentId` (foreign key to `customerSegments`), primary key (`customerId`, `customerSegmentId`).
5. `feedbackSurveys`: `id` (uuid, primary key), `userId` (foreign key to `users`), `title`, `description`, `createdAt`, `updatedAt`.
6. `surveyResponses`: `id` (uuid, primary key), `customerId` (foreign key to `customers`), `feedbackSurveyId` (foreign key to `feedbackSurveys`), `response` (jsonb), `submittedAt`.
7. `engagementHistory`: `id` (uuid, primary key), `customerId` (foreign key to `customers`), `eventType` (string, e.g., 'login', 'purchase', 'support_ticket'), `eventDate`, `details` (jsonb), `createdAt`.
**Core Functionalities (Implement full CRUD for each):**
1. **User Authentication:** Secure sign-up, login, and logout using NextAuth.js or a similar robust solution. Protect routes using session management.
2. **Customer Management:** Allow users to view, add, edit, and delete customers. Associate customers with the logged-in user. Implement import functionality from CSV/JSON.
3. **Customer Segmentation:** Enable users to create custom segments based on criteria like signup date, last engagement date, or custom tags. Assign customers to segments.
4. **Churn Risk Analysis (MVP):** Implement a basic churn risk scoring mechanism. Initially, this can be rule-based (e.g., low engagement score based on `engagementHistory` count and recency). Later, a simple ML model can be integrated. Display the `churnRiskScore` on the customer list and detail views.
5. **Feedback Collection:** Allow users to create simple feedback surveys (e.g., NPS, simple text input). Enable sending survey links to customers via email (mock implementation for MVP - just generate link).
6. **Engagement Tracking:** Manually log key customer interaction events (e.g., support ticket opened, feature used) with associated details. This data will feed into the churn risk score and segmentation.
7. **Dashboard:** A landing page (`app/page.tsx`) that provides an overview: Total Customers, Average Churn Risk Score, recent feedback summary, and a quick link to add a new customer.
**API Routes (`app/api/`):**
- Implement RESTful API endpoints for all CRUD operations on the defined database models. Ensure proper request validation and error handling.
- Example: `/api/customers` (GET, POST), `/api/customers/[id]` (GET, PUT, DELETE).
- `/api/analytics/churn-risk` (GET) to fetch aggregated churn risk data for the dashboard.
**Frontend:**
- Use React Server Components and Client Components appropriately within the `app/` directory.
- Employ Tailwind CSS for styling and ensure a responsive design.
- Build forms for creating/editing customers, segments, and surveys. Use libraries like `react-hook-form` for efficient form management.
- Display data in tables with sorting and filtering capabilities.
- Create dedicated pages for:
- Dashboard (`/`)
- Customers List (`/customers`)
- Customer Detail View (`/customers/[id]`)
- Segments Management (`/segments`)
- Feedback Surveys (`/surveys`)
**Technical Stack:**
- Next.js 13+ (App Router)
- TypeScript
- Drizzle ORM (for PostgreSQL)
- PostgreSQL (or a mock DB if local setup is complex for MVP)
- Tailwind CSS
- NextAuth.js (for authentication)
- React Hook Form (optional, for forms)
**Deployment Considerations (for MVP):**
- Ensure the code is structured for easy deployment on platforms like Vercel or Netlify.
**Important Notes:**
- Focus on core CRUD and the basic churn risk calculation for the MVP. Advanced features can be added later.
- Implement proper error handling and user feedback mechanisms throughout the application.
- Prioritize security, especially around authentication and data access.