#!/bin/bash

# TaxCore Service Startup Script
# This script starts the Node.js TaxCore service for handling FRCS API communication

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$SCRIPT_DIR"

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

echo -e "${GREEN}Starting TaxCore Service...${NC}"

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo -e "${RED}Error: Node.js is not installed${NC}"
    echo "Please install Node.js 14+ to continue"
    exit 1
fi

# Check if dependencies are installed
if [ ! -d "node_modules" ]; then
    echo -e "${YELLOW}Installing dependencies...${NC}"
    npm install
fi

# Check for certificate
CERT_PATH="${TAXCORE_PFX_PATH:-../FRCS_Certs_Install/LK2VRSH4-DeveloperAuthenticationCertificate.pfx}"
if [ ! -f "$CERT_PATH" ]; then
    echo -e "${YELLOW}Warning: Certificate not found at $CERT_PATH${NC}"
    echo "Service will attempt to autodiscover certificate..."
fi

# Load environment from .env if it exists
if [ -f "../.env" ]; then
    echo -e "${GREEN}Loading environment from .env${NC}"
    export $(cat ../.env | grep -v '^#' | xargs)
fi

# Set default port if not set
export TAXCORE_SERVICE_PORT="${TAXCORE_SERVICE_PORT:-3001}"

echo -e "${GREEN}Configuration:${NC}"
echo "  Port: $TAXCORE_SERVICE_PORT"
echo "  Certificate: $CERT_PATH"
echo "  Tax URL: ${TAXCORE_TAX_URL:-https://api.sandbox.vms.frcs.org.fj/api}"
echo "  VSDC URL: ${TAXCORE_VSDC_URL:-http://devesdc.sandbox.vms.frcs.org.fj:8888/...}"

# Check if port is already in use
if lsof -Pi :$TAXCORE_SERVICE_PORT -sTCP:LISTEN -t >/dev/null ; then
    echo -e "${YELLOW}Warning: Port $TAXCORE_SERVICE_PORT is already in use${NC}"
    read -p "Kill existing process and restart? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        lsof -ti:$TAXCORE_SERVICE_PORT | xargs kill -9
        echo -e "${GREEN}Killed existing process${NC}"
    else
        echo -e "${RED}Aborted${NC}"
        exit 1
    fi
fi

# Start service
echo -e "${GREEN}Starting service on port $TAXCORE_SERVICE_PORT...${NC}"
node taxcore-service.js
