#!/bin/bash

# Z.CRM - Quick Setup Script
# نظام إدارة علاقات العملاء - نظام إدارة شامل

set -e

echo "╔════════════════════════════════════════════════════════════╗"
echo "║                                                            ║"
echo "║  Z.CRM System - نظام إدارة علاقات العملاء                ║"
echo "║  Quick Setup Script                                        ║"
echo "║                                                            ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Check if Node.js is installed
echo -e "${BLUE}[1/8] Checking prerequisites...${NC}"
if ! command -v node &> /dev/null; then
    echo -e "${RED}❌ Node.js is not installed. Please install Node.js v18+ first.${NC}"
    exit 1
fi

NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 18 ]; then
    echo -e "${RED}❌ Node.js version must be 18 or higher. Current: $(node -v)${NC}"
    exit 1
fi

echo -e "${GREEN}✅ Node.js $(node -v) detected${NC}"

# Check if PostgreSQL is installed
if ! command -v psql &> /dev/null; then
    echo -e "${RED}❌ PostgreSQL is not installed. Please install PostgreSQL v14+ first.${NC}"
    exit 1
fi

echo -e "${GREEN}✅ PostgreSQL detected${NC}"

# Install root dependencies
echo ""
echo -e "${BLUE}[2/8] Installing root dependencies...${NC}"
npm install
echo -e "${GREEN}✅ Root dependencies installed${NC}"

# Install backend dependencies
echo ""
echo -e "${BLUE}[3/8] Installing backend dependencies...${NC}"
cd backend
npm install
echo -e "${GREEN}✅ Backend dependencies installed${NC}"

# Setup backend environment
echo ""
echo -e "${BLUE}[4/8] Setting up backend environment...${NC}"
if [ ! -f .env ]; then
    echo "Creating .env file..."
    cat > .env << EOL
# Server Configuration
NODE_ENV=development
PORT=5000
API_VERSION=v1

# Database
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/z_crm?schema=public"

# JWT
JWT_SECRET=z-crm-secret-key-change-this-in-production-$(date +%s)
JWT_EXPIRES_IN=7d
JWT_REFRESH_EXPIRES_IN=30d

# CORS
CORS_ORIGIN=http://localhost:3000

# File Upload
MAX_FILE_SIZE=10485760
UPLOAD_PATH=./uploads

# Pagination
DEFAULT_PAGE_SIZE=20
MAX_PAGE_SIZE=100

# Audit Log
AUDIT_LOG_RETENTION_DAYS=2555

# Security
BCRYPT_ROUNDS=10
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
EOL
    echo -e "${GREEN}✅ .env file created${NC}"
else
    echo -e "${GREEN}✅ .env file already exists${NC}"
fi

# Database setup
echo ""
echo -e "${BLUE}[5/8] Setting up database...${NC}"
echo "Creating database 'z_crm' (this might fail if it already exists, which is okay)..."
psql -U postgres -c "CREATE DATABASE z_crm;" 2>/dev/null || echo "Database might already exist"

echo "Running Prisma migrations..."
npx prisma generate
npx prisma migrate dev --name init
echo -e "${GREEN}✅ Database migrations completed${NC}"

# Seed database
echo ""
echo -e "${BLUE}[6/8] Seeding database with initial data...${NC}"
npm run prisma:seed
echo -e "${GREEN}✅ Database seeded successfully${NC}"

# Install frontend dependencies
echo ""
echo -e "${BLUE}[7/8] Installing frontend dependencies...${NC}"
cd ../frontend
npm install
echo -e "${GREEN}✅ Frontend dependencies installed${NC}"

# Setup frontend environment
if [ ! -f .env.local ]; then
    echo "NEXT_PUBLIC_API_URL=http://localhost:5000/api/v1" > .env.local
    echo -e "${GREEN}✅ Frontend .env.local created${NC}"
fi

# Return to root
cd ..

echo ""
echo -e "${BLUE}[8/8] Setup complete!${NC}"
echo ""
echo "╔════════════════════════════════════════════════════════════╗"
echo "║                                                            ║"
echo "║  ✅ Installation Complete!                                 ║"
echo "║                                                            ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""
echo -e "${GREEN}📋 Default Login Credentials:${NC}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "1. General Manager (Full Access)"
echo "   Email: gm@atmata.com"
echo "   Password: Admin@123"
echo ""
echo "2. Sales Manager"
echo "   Email: sales.manager@atmata.com"
echo "   Password: Admin@123"
echo ""
echo "3. Sales Representative"
echo "   Email: sales.rep@atmata.com"
echo "   Password: Admin@123"
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo -e "${BLUE}🚀 To start the application:${NC}"
echo ""
echo "   npm run dev"
echo ""
echo -e "${BLUE}📖 Access the application:${NC}"
echo ""
echo "   Frontend: http://localhost:3000"
echo "   Backend API: http://localhost:5000"
echo "   Database GUI: npm run prisma:studio (in backend folder)"
echo ""
echo -e "${BLUE}📚 Documentation:${NC}"
echo ""
echo "   Installation Guide: INSTALLATION.md"
echo "   API Documentation: API_DOCUMENTATION.md"
echo "   Main README: README.md"
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo -e "${GREEN}Happy coding! مجموعة أتمتة${NC}"
echo ""

