CREATE TABLE IF NOT EXISTS unidesk_nodes (
  provider_id TEXT PRIMARY KEY,
  name TEXT NOT NULL,
  labels JSONB NOT NULL DEFAULT '{}'::jsonb,
  status TEXT NOT NULL,
  connected_at TIMESTAMPTZ,
  last_heartbeat TIMESTAMPTZ,
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS unidesk_events (
  id BIGSERIAL PRIMARY KEY,
  type TEXT NOT NULL,
  source TEXT NOT NULL,
  payload JSONB NOT NULL DEFAULT '{}'::jsonb,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS unidesk_tasks (
  id TEXT PRIMARY KEY,
  provider_id TEXT NOT NULL,
  command TEXT NOT NULL,
  status TEXT NOT NULL,
  payload JSONB NOT NULL DEFAULT '{}'::jsonb,
  result JSONB,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS unidesk_node_docker_status (
  provider_id TEXT PRIMARY KEY,
  status JSONB NOT NULL DEFAULT '{}'::jsonb,
  collected_at TIMESTAMPTZ,
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS unidesk_node_system_status (
  provider_id TEXT PRIMARY KEY,
  status JSONB NOT NULL DEFAULT '{}'::jsonb,
  collected_at TIMESTAMPTZ,
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS unidesk_node_metric_samples (
  id BIGSERIAL PRIMARY KEY,
  provider_id TEXT NOT NULL,
  collected_at TIMESTAMPTZ NOT NULL,
  cpu_percent DOUBLE PRECISION NOT NULL DEFAULT 0,
  memory_percent DOUBLE PRECISION NOT NULL DEFAULT 0,
  disk_percent DOUBLE PRECISION NOT NULL DEFAULT 0,
  sample JSONB NOT NULL DEFAULT '{}'::jsonb,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_unidesk_nodes_status ON unidesk_nodes(status);
CREATE INDEX IF NOT EXISTS idx_unidesk_events_created_at ON unidesk_events(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_unidesk_tasks_provider_status ON unidesk_tasks(provider_id, status);
CREATE INDEX IF NOT EXISTS idx_unidesk_node_docker_status_updated_at ON unidesk_node_docker_status(updated_at DESC);
CREATE INDEX IF NOT EXISTS idx_unidesk_node_system_status_updated_at ON unidesk_node_system_status(updated_at DESC);
CREATE INDEX IF NOT EXISTS idx_unidesk_node_metric_samples_provider_time ON unidesk_node_metric_samples(provider_id, collected_at DESC);
