CREATE TABLE IF NOT EXISTS tina_kv (
  key VARCHAR(512) NOT NULL,
  value JSONB NOT NULL,
  namespace VARCHAR(100) NOT NULL DEFAULT 'main',
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (key, namespace)
);

CREATE INDEX IF NOT EXISTS idx_namespace ON tina_kv(namespace);
CREATE INDEX IF NOT EXISTS idx_updated ON tina_kv(updated_at);

-- Fonction pour mise à jour automatique du updated_at
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = CURRENT_TIMESTAMP;
  RETURN NEW;
END;
$$ language 'plpgsql';

CREATE TRIGGER update_tina_kv_updated_at
  BEFORE UPDATE ON tina_kv
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at_column();
