#!/usr/bin/env bash
#
# Run this script after `git pull` on the server to apply new migrations
# and seeders for the central database and all tenant databases.
#
# Usage (from project root):
#   ./scripts/deploy.sh
#   bash scripts/deploy.sh
#
# Or from anywhere:
#   /path/to/sellzaki/scripts/deploy.sh
#
set -e

# Project root: resolve if we're in scripts/ or project root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$ROOT_DIR"

echo "==> Deploying from: $ROOT_DIR"

# Writable storage for legacy POS import uploads (manage admin)
mkdir -p storage/app/legacy-imports
chmod -R ug+rwx storage bootstrap/cache 2>/dev/null || true

# 1. Central database migrations
echo "==> Running central migrations..."
php artisan migrate --force

# 2. Tenant migrations (skip tenants that have no database yet)
echo "==> Running migrations for all tenants..."
php artisan tenants:migrate-all --skip-missing

# 3. Tenant seeders (DatabaseSeeder for each tenant; skip missing DBs)
echo "==> Running seeders for all tenants..."
php artisan tenants:seed-all --skip-missing

# 4. Ensure support@sellzaki.com exists in every tenant (idempotent)
echo "==> Ensuring support user in all tenants..."
php artisan tenant:seed-support-user

echo "==> Deploy finished successfully."
