#!/bin/bash

###############################################################################
# Fresh Database Setup Script
# 
# Purpose: Complete fresh database setup for Royal Enfield Workflow System
# 
# Prerequisites:
# 1. PostgreSQL 16.x installed
# 2. Redis installed and running
# 3. Node.js 18+ installed
# 4. Environment variables configured in .env
# 
# Usage:
#   chmod +x scripts/fresh-database-setup.sh
#   ./scripts/fresh-database-setup.sh
# 
# What this script does:
# 1. Drops existing database (if exists)
# 2. Creates fresh database
# 3. Runs all migrations in order
# 4. Seeds admin configuration
# 5. Creates initial admin user
# 6. Verifies setup
###############################################################################

set -e  # Exit on error

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Load environment variables
if [ -f .env ]; then
  echo -e "${BLUE}📋 Loading environment variables...${NC}"
  export $(cat .env | grep -v '^#' | xargs)
else
  echo -e "${RED}❌ .env file not found!${NC}"
  echo -e "${YELLOW}Please copy env.example to .env and configure it${NC}"
  exit 1
fi

# Database variables
DB_NAME="${DB_NAME:-royal_enfield_workflow}"
DB_USER="${DB_USER:-postgres}"
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"

echo -e "${BLUE}╔═══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║  Royal Enfield Workflow System - Fresh Database Setup        ║${NC}"
echo -e "${BLUE}╚═══════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${YELLOW}⚠️  WARNING: This will DROP the existing database!${NC}"
echo -e "${YELLOW}    Database: ${DB_NAME}${NC}"
echo -e "${YELLOW}    Host: ${DB_HOST}:${DB_PORT}${NC}"
echo ""
read -p "Are you sure you want to continue? (yes/no): " -r
echo ""

if [[ ! $REPLY =~ ^[Yy]es$ ]]; then
  echo -e "${YELLOW}Setup cancelled.${NC}"
  exit 0
fi

echo -e "${BLUE}════════════════════════════════════════════════════════════════${NC}"
echo -e "${BLUE}Step 1: Dropping existing database (if exists)...${NC}"
echo -e "${BLUE}════════════════════════════════════════════════════════════════${NC}"

psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d postgres -c "DROP DATABASE IF EXISTS $DB_NAME;" || true

echo -e "${GREEN}✅ Old database dropped${NC}"
echo ""

echo -e "${BLUE}════════════════════════════════════════════════════════════════${NC}"
echo -e "${BLUE}Step 2: Creating fresh database...${NC}"
echo -e "${BLUE}════════════════════════════════════════════════════════════════${NC}"

psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d postgres -c "CREATE DATABASE $DB_NAME OWNER $DB_USER;"

echo -e "${GREEN}✅ Fresh database created: $DB_NAME${NC}"
echo ""

echo -e "${BLUE}════════════════════════════════════════════════════════════════${NC}"
echo -e "${BLUE}Step 3: Installing PostgreSQL extensions...${NC}"
echo -e "${BLUE}════════════════════════════════════════════════════════════════${NC}"

psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME <<EOF
-- UUID extension for primary keys
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- pg_trgm for text search
CREATE EXTENSION IF NOT EXISTS "pg_trgm";

-- Enable JSONB operators
CREATE EXTENSION IF NOT EXISTS "btree_gin";
EOF

echo -e "${GREEN}✅ PostgreSQL extensions installed${NC}"
echo ""

echo -e "${BLUE}════════════════════════════════════════════════════════════════${NC}"
echo -e "${BLUE}Step 4: Running database migrations...${NC}"
echo -e "${BLUE}════════════════════════════════════════════════════════════════${NC}"

npm run migrate

echo -e "${GREEN}✅ All migrations completed${NC}"
echo ""

echo -e "${BLUE}════════════════════════════════════════════════════════════════${NC}"
echo -e "${BLUE}Step 5: Seeding admin configuration...${NC}"
echo -e "${BLUE}════════════════════════════════════════════════════════════════${NC}"

npm run seed:config

echo -e "${GREEN}✅ Admin configuration seeded${NC}"
echo ""

echo -e "${BLUE}════════════════════════════════════════════════════════════════${NC}"
echo -e "${BLUE}Step 6: Database verification...${NC}"
echo -e "${BLUE}════════════════════════════════════════════════════════════════${NC}"

psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME <<EOF
-- Check tables created
SELECT 
  schemaname,
  tablename 
FROM pg_tables 
WHERE schemaname = 'public' 
ORDER BY tablename;

-- Check role enum
SELECT 
  enumlabel 
FROM pg_enum 
WHERE enumtypid = 'user_role_enum'::regtype;

-- Check indexes
SELECT 
  tablename, 
  indexname 
FROM pg_indexes 
WHERE schemaname = 'public' AND tablename = 'users'
ORDER BY tablename, indexname;
EOF

echo -e "${GREEN}✅ Database structure verified${NC}"
echo ""

echo -e "${GREEN}╔═══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║              ✅ FRESH DATABASE SETUP COMPLETE!                 ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${YELLOW}📋 Next Steps:${NC}"
echo -e "   1. Assign admin role to your user:"
echo -e "      ${BLUE}psql -d $DB_NAME -f scripts/assign-admin-user.sql${NC}"
echo ""
echo -e "   2. Start the backend server:"
echo -e "      ${BLUE}npm run dev${NC}"
echo ""
echo -e "   3. Access the application:"
echo -e "      ${BLUE}http://localhost:5000${NC}"
echo ""
echo -e "${GREEN}🎉 Database is ready for production use!${NC}"

