-- ============================================================
-- FreightDesk — Migration 003: Soft Delete + Security
-- ============================================================

-- Add soft-delete columns
ALTER TABLE loads ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
ALTER TABLE payments ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
ALTER TABLE shippers ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
ALTER TABLE vehicles ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;

-- Add role column to portal_users if not exists
ALTER TABLE portal_users ADD COLUMN IF NOT EXISTS role TEXT DEFAULT 'admin';

-- Add index for soft-delete queries
CREATE INDEX IF NOT EXISTS idx_loads_deleted_at ON loads(deleted_at) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_payments_deleted_at ON payments(deleted_at) WHERE deleted_at IS NULL;

-- Add load_count to shippers for quick reference
ALTER TABLE shippers ADD COLUMN IF NOT EXISTS load_count INTEGER DEFAULT 0;

-- Update load_count for existing shippers
UPDATE shippers SET load_count = (
  SELECT COUNT(*) FROM loads WHERE loads.shipper_id = shippers.id
);
