-- IT0 Seed Data
-- Replace {SCHEMA} with tenant schema (e.g., it0_t_t001)
-- Replace {TENANT_ID} with tenant ID (e.g., t001)

SET search_path TO {SCHEMA};

-- =========================================================================
-- Users (password: "admin123" hashed with bcryptjs)
-- =========================================================================

INSERT INTO users (id, tenant_id, email, password_hash, name, roles, is_active) VALUES
  ('a0000001-0000-0000-0000-000000000001', '{TENANT_ID}', 'admin@demo.it0.dev', '$2a$10$8KzaNdKXaLQhF3G4JKH.XeaHjZkBgjxJGPZ5k3fDkNyBk1CZ7Wz2e', 'Admin User', '{admin}', TRUE),
  ('a0000001-0000-0000-0000-000000000002', '{TENANT_ID}', 'operator@demo.it0.dev', '$2a$10$8KzaNdKXaLQhF3G4JKH.XeaHjZkBgjxJGPZ5k3fDkNyBk1CZ7Wz2e', 'Ops Operator', '{operator}', TRUE),
  ('a0000001-0000-0000-0000-000000000003', '{TENANT_ID}', 'viewer@demo.it0.dev', '$2a$10$8KzaNdKXaLQhF3G4JKH.XeaHjZkBgjxJGPZ5k3fDkNyBk1CZ7Wz2e', 'Readonly Viewer', '{viewer}', TRUE)
ON CONFLICT DO NOTHING;

-- =========================================================================
-- Roles
-- =========================================================================

INSERT INTO roles (id, tenant_id, name, permissions, description) VALUES
  (gen_random_uuid(), '{TENANT_ID}', 'admin', '{servers:*,clusters:*,credentials:*,runbooks:*,standing_orders:*,skills:*,hooks:*,alerts:*,audit:read,settings:*,users:*}', 'Full platform access'),
  (gen_random_uuid(), '{TENANT_ID}', 'operator', '{servers:read,servers:execute,clusters:read,credentials:read,runbooks:read,runbooks:execute,standing_orders:read,skills:read,alerts:read,alerts:acknowledge,audit:read}', 'Can execute operations and acknowledge alerts'),
  (gen_random_uuid(), '{TENANT_ID}', 'viewer', '{servers:read,clusters:read,alerts:read,audit:read,runbooks:read,standing_orders:read}', 'Read-only access to all resources')
ON CONFLICT DO NOTHING;

-- =========================================================================
-- Credentials (demo SSH key — encrypted value is placeholder)
-- =========================================================================

INSERT INTO credentials (id, tenant_id, name, type, encrypted_value, iv, fingerprint, key_type, created_by) VALUES
  ('c0000001-0000-0000-0000-000000000001', '{TENANT_ID}', 'dev-ssh-key', 'ssh_key', E'\\x00', E'\\x00', 'SHA256:demo_fingerprint_dev', 'ed25519', 'a0000001-0000-0000-0000-000000000001'),
  ('c0000001-0000-0000-0000-000000000002', '{TENANT_ID}', 'prod-ssh-key', 'ssh_key', E'\\x00', E'\\x00', 'SHA256:demo_fingerprint_prod', 'rsa', 'a0000001-0000-0000-0000-000000000001')
ON CONFLICT DO NOTHING;

-- =========================================================================
-- Clusters
-- =========================================================================

INSERT INTO clusters (id, tenant_id, name, type, environment, description) VALUES
  ('d0000001-0000-0000-0000-000000000001', '{TENANT_ID}', 'dev-cluster', 'bare_metal', 'dev', 'Development environment servers'),
  ('d0000001-0000-0000-0000-000000000002', '{TENANT_ID}', 'prod-web-tier', 'bare_metal', 'prod', 'Production web application tier'),
  ('d0000001-0000-0000-0000-000000000003', '{TENANT_ID}', 'prod-k8s', 'k8s', 'prod', 'Production Kubernetes cluster')
ON CONFLICT DO NOTHING;

-- =========================================================================
-- Servers
-- =========================================================================

INSERT INTO servers (id, tenant_id, name, host, port, environment, role, cluster_id, ssh_user, credential_id, network_type, tags, status, description) VALUES
  ('e0000001-0000-0000-0000-000000000001', '{TENANT_ID}', 'dev-web-01', '10.0.1.10', 22, 'dev', 'web', 'd0000001-0000-0000-0000-000000000001', 'deploy', 'c0000001-0000-0000-0000-000000000001', 'private', '{"os": "ubuntu-22.04", "region": "us-east-1"}', 'active', 'Dev web server'),
  ('e0000001-0000-0000-0000-000000000002', '{TENANT_ID}', 'dev-db-01', '10.0.1.20', 22, 'dev', 'db', 'd0000001-0000-0000-0000-000000000001', 'deploy', 'c0000001-0000-0000-0000-000000000001', 'private', '{"os": "ubuntu-22.04", "db": "postgresql-16"}', 'active', 'Dev database server'),
  ('e0000001-0000-0000-0000-000000000003', '{TENANT_ID}', 'prod-web-01', '10.1.1.10', 22, 'prod', 'web', 'd0000001-0000-0000-0000-000000000002', 'deploy', 'c0000001-0000-0000-0000-000000000002', 'private', '{"os": "ubuntu-22.04", "region": "us-east-1"}', 'active', 'Production web server 1'),
  ('e0000001-0000-0000-0000-000000000004', '{TENANT_ID}', 'prod-web-02', '10.1.1.11', 22, 'prod', 'web', 'd0000001-0000-0000-0000-000000000002', 'deploy', 'c0000001-0000-0000-0000-000000000002', 'private', '{"os": "ubuntu-22.04", "region": "us-east-1"}', 'active', 'Production web server 2'),
  ('e0000001-0000-0000-0000-000000000005', '{TENANT_ID}', 'prod-db-01', '10.1.2.10', 22, 'prod', 'db', NULL, 'deploy', 'c0000001-0000-0000-0000-000000000002', 'private', '{"os": "ubuntu-22.04", "db": "postgresql-16", "role": "primary"}', 'active', 'Production primary database'),
  ('e0000001-0000-0000-0000-000000000006', '{TENANT_ID}', 'prod-cache-01', '10.1.3.10', 22, 'prod', 'cache', NULL, 'deploy', 'c0000001-0000-0000-0000-000000000002', 'private', '{"os": "ubuntu-22.04", "cache": "redis-7"}', 'active', 'Production Redis cache')
ON CONFLICT DO NOTHING;

-- =========================================================================
-- Alert Rules
-- =========================================================================

INSERT INTO alert_rules (id, tenant_id, name, metric_type, condition, severity, target_servers, is_active) VALUES
  (gen_random_uuid(), '{TENANT_ID}', 'High CPU Usage', 'cpu', '{"operator": ">", "threshold": 90, "durationSeconds": 300}', 'warning', NULL, TRUE),
  (gen_random_uuid(), '{TENANT_ID}', 'Critical CPU Usage', 'cpu', '{"operator": ">", "threshold": 98, "durationSeconds": 60}', 'critical', NULL, TRUE),
  (gen_random_uuid(), '{TENANT_ID}', 'High Memory Usage', 'memory', '{"operator": ">", "threshold": 85, "durationSeconds": 300}', 'warning', NULL, TRUE),
  (gen_random_uuid(), '{TENANT_ID}', 'Disk Space Low', 'disk', '{"operator": ">", "threshold": 90, "durationSeconds": 600}', 'critical', NULL, TRUE),
  (gen_random_uuid(), '{TENANT_ID}', 'Network Packet Loss', 'network', '{"operator": ">", "threshold": 5, "durationSeconds": 120}', 'warning', NULL, TRUE)
ON CONFLICT DO NOTHING;

-- =========================================================================
-- Runbooks
-- =========================================================================

INSERT INTO runbooks (id, tenant_id, name, description, trigger_type, prompt_template, allowed_tools, max_risk_level, auto_approve, is_active) VALUES
  (gen_random_uuid(), '{TENANT_ID}', 'Server Health Check', 'Run comprehensive health check on target servers', 'manual',
   E'Check the health of the target servers:\n1. Verify SSH connectivity\n2. Check CPU, memory, and disk usage\n3. Verify critical services are running (nginx, postgresql, redis)\n4. Check recent system logs for errors\n5. Report any anomalies found',
   '{Bash,Read,Grep}', 0, TRUE, TRUE),

  (gen_random_uuid(), '{TENANT_ID}', 'Log Analysis', 'Analyze system logs for errors and anomalies', 'manual',
   E'Analyze system logs on the target servers:\n1. Check /var/log/syslog for errors in the last hour\n2. Check application logs for exceptions\n3. Look for any OOM killer events\n4. Check for failed SSH login attempts\n5. Summarize findings with severity assessment',
   '{Bash,Read,Grep,Glob}', 0, TRUE, TRUE),

  (gen_random_uuid(), '{TENANT_ID}', 'Auto-Scale Response', 'Respond to high CPU alert by scaling resources', 'alert',
   E'A high CPU alert has been triggered. Investigate and respond:\n1. Identify the process consuming most CPU\n2. Check if it is a legitimate workload spike\n3. If nginx/web traffic spike, suggest scaling actions\n4. If runaway process, recommend termination\n5. Report findings and actions taken',
   '{Bash,Read}', 1, FALSE, TRUE),

  (gen_random_uuid(), '{TENANT_ID}', 'Nginx Restart Procedure', 'Safely restart Nginx with validation', 'manual',
   E'Perform a safe Nginx restart:\n1. Test nginx configuration: nginx -t\n2. If config OK, gracefully reload: systemctl reload nginx\n3. Verify nginx is serving traffic\n4. Check error logs after reload\n5. Report status',
   '{Bash,Read}', 1, FALSE, TRUE)
ON CONFLICT DO NOTHING;

-- =========================================================================
-- Standing Orders
-- =========================================================================

INSERT INTO standing_orders (id, tenant_id, name, description, defined_in_session_id, trigger_type, trigger_config, targets, agent_prompt, max_risk_level, max_turns, max_budget_usd, decision_boundary, status, created_by) VALUES
  ('so-daily-health', '{TENANT_ID}', 'Daily Health Check', 'Run health checks every day at 2am', '00000000-0000-0000-0000-000000000000', 'cron',
   '{"cronExpression": "0 2 * * *"}',
   '{"allServers": true}',
   E'Run a comprehensive health check on all servers. Check CPU, memory, disk usage, and service status. Report any anomalies.',
   0, 20, 0.50,
   '{"allowedActions": ["read_metrics", "check_service"], "escalateConditions": ["server_down", "disk_full"], "escalationRules": [{"condition": "server_down", "channel": "push", "priority": "urgent"}]}',
   'active', 'a0000001-0000-0000-0000-000000000001'),

  ('so-disk-watch', '{TENANT_ID}', 'Disk Space Watchdog', 'Monitor disk space and clean temp files when > 85%', '00000000-0000-0000-0000-000000000000', 'threshold',
   '{"metricType": "disk", "operator": ">", "value": 85, "durationSeconds": 60}',
   '{"environmentFilter": ["prod"]}',
   E'Disk usage is above 85%. Investigate and clean up:\n1. Find large files in /tmp and /var/log\n2. Clean old log files older than 7 days\n3. Remove any core dumps\n4. Report space recovered',
   1, 15, 0.30,
   '{"allowedActions": ["clean_temp", "rotate_logs"], "escalateConditions": ["disk_above_95"], "escalationRules": [{"condition": "disk_above_95", "channel": "voice_call", "priority": "urgent"}]}',
   'active', 'a0000001-0000-0000-0000-000000000001')
ON CONFLICT DO NOTHING;

-- =========================================================================
-- Skills
-- =========================================================================

INSERT INTO skills (id, tenant_id, name, category, description, content, tags, is_active) VALUES
  (gen_random_uuid(), '{TENANT_ID}', 'linux-diagnostics', 'system',
   'Linux server diagnostics commands and procedures',
   E'# Linux Diagnostics Skill\n\n## CPU Analysis\n- `top -bn1 | head -20` — snapshot of processes\n- `mpstat -P ALL 1 3` — per-CPU stats\n\n## Memory Analysis\n- `free -h` — memory overview\n- `vmstat 1 5` — virtual memory stats\n\n## Disk Analysis\n- `df -h` — filesystem usage\n- `du -sh /var/log/*` — log directory sizes\n- `find /tmp -type f -mtime +7` — old temp files\n\n## Network\n- `ss -tuln` — listening ports\n- `ping -c 3 <host>` — connectivity check',
   '{linux,diagnostics,system}', TRUE),

  (gen_random_uuid(), '{TENANT_ID}', 'nginx-ops', 'web',
   'Nginx operations and troubleshooting',
   E'# Nginx Operations Skill\n\n## Configuration\n- `nginx -t` — test configuration\n- `nginx -T` — dump full config\n\n## Service Management\n- `systemctl status nginx`\n- `systemctl reload nginx` — graceful reload\n- `systemctl restart nginx` — full restart (drops connections)\n\n## Troubleshooting\n- `tail -f /var/log/nginx/error.log`\n- `tail -f /var/log/nginx/access.log`\n- `curl -I http://localhost` — check local response',
   '{nginx,web,http}', TRUE),

  (gen_random_uuid(), '{TENANT_ID}', 'postgresql-ops', 'database',
   'PostgreSQL operations and monitoring',
   E'# PostgreSQL Operations Skill\n\n## Status\n- `systemctl status postgresql`\n- `pg_isready` — check if accepting connections\n\n## Monitoring Queries\n- Active connections: `SELECT count(*) FROM pg_stat_activity;`\n- Long queries: `SELECT pid, now()-query_start AS duration, query FROM pg_stat_activity WHERE state != ''idle'' ORDER BY duration DESC LIMIT 5;`\n- Database sizes: `SELECT pg_database.datname, pg_size_pretty(pg_database_size(pg_database.datname)) FROM pg_database ORDER BY pg_database_size(pg_database.datname) DESC;`\n\n## Maintenance\n- `VACUUM ANALYZE;` — reclaim space and update stats\n- `pg_dump -Fc dbname > backup.dump` — backup',
   '{postgresql,database,sql}', TRUE)
ON CONFLICT DO NOTHING;

-- =========================================================================
-- Hook Scripts
-- =========================================================================

INSERT INTO hook_scripts (id, tenant_id, name, event, tool_pattern, script, timeout, enabled, description) VALUES
  (gen_random_uuid(), '{TENANT_ID}', 'audit-bash-commands', 'PostToolUse', 'Bash',
   E'#!/bin/bash\n# Log all executed Bash commands to audit\necho "[AUDIT] $(date -Iseconds) Tool=Bash Command=$TOOL_INPUT" >> /var/log/it0-audit.log\nexit 0',
   10, TRUE, 'Logs all Bash tool invocations to audit file'),

  (gen_random_uuid(), '{TENANT_ID}', 'block-rm-rf', 'PreToolUse', 'Bash',
   E'#!/bin/bash\n# Block dangerous rm -rf commands\nif echo "$TOOL_INPUT" | grep -qE "rm\\s+(-rf|-fr|--no-preserve-root)\\s+/"; then\n  echo "BLOCKED: Potentially destructive rm command detected"\n  exit 1\nfi\nexit 0',
   5, TRUE, 'Blocks rm -rf / and similar destructive commands')
ON CONFLICT DO NOTHING;

-- =========================================================================
-- Escalation Policies
-- =========================================================================

INSERT INTO escalation_policies (id, tenant_id, name, severity, steps, is_default) VALUES
  (gen_random_uuid(), '{TENANT_ID}', 'Default Critical', 'critical',
   '[{"delaySeconds": 0, "channel": "push"}, {"delaySeconds": 300, "channel": "sms"}, {"delaySeconds": 600, "channel": "voice_call"}]',
   TRUE),
  (gen_random_uuid(), '{TENANT_ID}', 'Default Warning', 'warning',
   '[{"delaySeconds": 0, "channel": "push"}, {"delaySeconds": 900, "channel": "email"}]',
   FALSE)
ON CONFLICT DO NOTHING;

-- =========================================================================
-- Contacts
-- =========================================================================

INSERT INTO contacts (id, tenant_id, user_id, name, phone, email, preferred_channel, is_active) VALUES
  (gen_random_uuid(), '{TENANT_ID}', 'a0000001-0000-0000-0000-000000000001', 'Admin User', '+1234567890', 'admin@demo.it0.dev', 'push', TRUE),
  (gen_random_uuid(), '{TENANT_ID}', 'a0000001-0000-0000-0000-000000000002', 'Ops Operator', '+1234567891', 'operator@demo.it0.dev', 'push', TRUE)
ON CONFLICT DO NOTHING;
