-- AUTO-GENERATED FILE - DO NOT EDIT MANUALLY
-- Generated from Jira Assets Schema via REST API
-- PostgreSQL version
-- Generated at: 2026-01-09T02:12:50.973Z
--
-- Re-generate with: npm run generate-schema

-- =============================================================================
-- Core Tables
-- =============================================================================

-- Cached CMDB objects (all types stored in single table with JSON data)
CREATE TABLE IF NOT EXISTS cached_objects (
  id TEXT PRIMARY KEY,
  object_key TEXT NOT NULL UNIQUE,
  object_type TEXT NOT NULL,
  label TEXT NOT NULL,
  data JSONB NOT NULL,
  jira_updated_at TEXT,
  jira_created_at TEXT,
  cached_at TEXT NOT NULL
);

-- Object relations (references between objects)
CREATE TABLE IF NOT EXISTS object_relations (
  id SERIAL PRIMARY KEY,
  source_id TEXT NOT NULL,
  target_id TEXT NOT NULL,
  attribute_name TEXT NOT NULL,
  source_type TEXT NOT NULL,
  target_type TEXT NOT NULL,
  UNIQUE(source_id, target_id, attribute_name)
);

-- Sync metadata (tracks sync state)
CREATE TABLE IF NOT EXISTS sync_metadata (
  key TEXT PRIMARY KEY,
  value TEXT NOT NULL,
  updated_at TEXT NOT NULL
);

-- =============================================================================
-- Indices for Performance
-- =============================================================================

CREATE INDEX IF NOT EXISTS idx_objects_type ON cached_objects(object_type);
CREATE INDEX IF NOT EXISTS idx_objects_key ON cached_objects(object_key);
CREATE INDEX IF NOT EXISTS idx_objects_updated ON cached_objects(jira_updated_at);
CREATE INDEX IF NOT EXISTS idx_objects_label ON cached_objects(label);
CREATE INDEX IF NOT EXISTS idx_objects_data_gin ON cached_objects USING GIN (data);

CREATE INDEX IF NOT EXISTS idx_relations_source ON object_relations(source_id);
CREATE INDEX IF NOT EXISTS idx_relations_target ON object_relations(target_id);
CREATE INDEX IF NOT EXISTS idx_relations_source_type ON object_relations(source_type);
CREATE INDEX IF NOT EXISTS idx_relations_target_type ON object_relations(target_type);
CREATE INDEX IF NOT EXISTS idx_relations_attr ON object_relations(attribute_name);
