-- kalendar_events_20260505.sql
-- PGZ Sport — Kalendar (events) CRUD table
-- Author: dradulic@outlook.com / damir@rinet.one
-- Date: 2026-05-05
-- Purpose: User-managed calendar events (meetings, manifestations,
--          medical slots, training, custom termini). Drives /app#kalendar.

BEGIN;

CREATE TABLE IF NOT EXISTS pgz_sport.kalendar_events (
  id          BIGSERIAL PRIMARY KEY,
  title       TEXT NOT NULL,
  start_at    TIMESTAMPTZ NOT NULL,
  end_at      TIMESTAMPTZ,
  location    TEXT,
  description TEXT,
  event_type  TEXT DEFAULT 'event'
              CHECK (event_type IN ('event','meeting','manif','training','medical','other')),
  color       TEXT DEFAULT 'b'  CHECK (color IN ('a','b','g','r')),
  klub_id     BIGINT REFERENCES pgz_sport.klubovi(id) ON DELETE SET NULL,
  savez_id    BIGINT REFERENCES pgz_sport.savezi(id)  ON DELETE SET NULL,
  created_by  BIGINT REFERENCES pgz_sport.users(id)   ON DELETE SET NULL,
  created_at  TIMESTAMPTZ DEFAULT now(),
  updated_at  TIMESTAMPTZ DEFAULT now()
);

CREATE INDEX IF NOT EXISTS ix_kalendar_events_start_at ON pgz_sport.kalendar_events (start_at);
CREATE INDEX IF NOT EXISTS ix_kalendar_events_klub     ON pgz_sport.kalendar_events (klub_id);
CREATE INDEX IF NOT EXISTS ix_kalendar_events_savez    ON pgz_sport.kalendar_events (savez_id);
CREATE INDEX IF NOT EXISTS ix_kalendar_events_creator  ON pgz_sport.kalendar_events (created_by);

-- updated_at trigger
CREATE OR REPLACE FUNCTION pgz_sport._kalendar_events_touch() RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = now();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trg_kalendar_events_touch ON pgz_sport.kalendar_events;
CREATE TRIGGER trg_kalendar_events_touch
  BEFORE UPDATE ON pgz_sport.kalendar_events
  FOR EACH ROW EXECUTE FUNCTION pgz_sport._kalendar_events_touch();

COMMIT;
