-- Migration Phase 2-8 — 13 avril 2026
-- Execute sur prro3328_mafiazworld via cPanel phpPgAdmin

-- 1. Business economy columns
ALTER TABLE businesses ADD COLUMN IF NOT EXISTS cash_register integer DEFAULT 0;
ALTER TABLE businesses ADD COLUMN IF NOT EXISTS closed_until timestamp;
ALTER TABLE businesses ADD COLUMN IF NOT EXISTS last_extorted_by jsonb DEFAULT '{}';
ALTER TABLE businesses ADD COLUMN IF NOT EXISTS last_robbed_at timestamp;

-- 2. GangMember hit_points
ALTER TABLE gang_members ADD COLUMN IF NOT EXISTS hit_points integer DEFAULT 100;

-- 3. Player territory_hp
ALTER TABLE players ADD COLUMN IF NOT EXISTS territory_hp integer DEFAULT 1000;

-- 4. Police units table
CREATE TABLE IF NOT EXISTS police_units (
  id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
  type varchar(30) DEFAULT 'patrol_foot' NOT NULL,
  agents_count integer DEFAULT 1,
  weapons jsonb DEFAULT '[]',
  vision_km decimal(4,2) DEFAULT 0.2,
  radio_km decimal(4,2) DEFAULT 5.0,
  speed_kmh integer DEFAULT 5,
  current_lat decimal(10,8),
  current_lon decimal(11,8),
  patrol_center_lat decimal(10,8) NOT NULL,
  patrol_center_lon decimal(11,8) NOT NULL,
  patrol_radius_km decimal(4,2) DEFAULT 0.98,
  status varchar(20) DEFAULT 'patrolling',
  dest_lat decimal(10,8),
  dest_lon decimal(11,8),
  eta timestamp,
  target_player_id uuid,
  heat_threshold integer DEFAULT 0,
  is_active boolean DEFAULT true,
  created_at timestamp DEFAULT NOW(),
  updated_at timestamp DEFAULT NOW()
);

-- 5. Add type enum for police_units (if needed, may already exist from TypeORM sync)
-- TypeORM handles enum creation automatically with synchronize:true

-- 6. Initialize cash_register for existing businesses (set to revenue_per_day * random 0-12h)
UPDATE businesses SET cash_register = GREATEST(0, FLOOR(revenue_per_day / 24 * (RANDOM() * 12)));

-- 7. Initialize territory_hp for existing players
UPDATE players SET territory_hp = 1000 WHERE territory_hp IS NULL OR territory_hp = 0;

-- 8. Initialize hit_points for existing gang_members based on grade
UPDATE gang_members SET hit_points = 100 + (grade * 15) WHERE hit_points IS NULL OR hit_points = 0;
