-- Create enums for AI Courses
DO $$ BEGIN
  CREATE TYPE forma_kurzu_enum AS ENUM ('prezencne', 'online', 'hybridne');
EXCEPTION
  WHEN duplicate_object THEN null;
END $$;

DO $$ BEGIN
  CREATE TYPE stav_registracie_enum AS ENUM ('potencialny', 'registrovany', 'potvrdeny', 'absolvoval', 'zruseny');
EXCEPTION
  WHEN duplicate_object THEN null;
END $$;

DO $$ BEGIN
  CREATE TYPE typ_prilohy_enum AS ENUM ('certifikat', 'faktura', 'prihlaska', 'doklad_o_platbe', 'ine');
EXCEPTION
  WHEN duplicate_object THEN null;
END $$;

-- Create kurzy table (AI courses)
CREATE TABLE IF NOT EXISTS kurzy (
  id SERIAL PRIMARY KEY,
  nazov VARCHAR(255) NOT NULL,
  typ_kurzu VARCHAR(100) NOT NULL,
  popis TEXT,
  cena NUMERIC(10, 2) NOT NULL,
  datum_od DATE NOT NULL,
  datum_do DATE NOT NULL,
  max_kapacita INTEGER,
  aktivny BOOLEAN DEFAULT TRUE NOT NULL,
  created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,
  updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL
);

-- Create ucastnici table (participants)
CREATE TABLE IF NOT EXISTS ucastnici (
  id SERIAL PRIMARY KEY,
  titul VARCHAR(50),
  meno VARCHAR(100) NOT NULL,
  priezvisko VARCHAR(100) NOT NULL,
  email VARCHAR(255) NOT NULL UNIQUE,
  telefon VARCHAR(50),
  firma VARCHAR(255),
  mesto VARCHAR(100),
  ulica VARCHAR(255),
  psc VARCHAR(10),
  created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,
  updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL
);

CREATE UNIQUE INDEX IF NOT EXISTS ucastnici_email_idx ON ucastnici(email);

-- Create registracie table (registrations)
CREATE TABLE IF NOT EXISTS registracie (
  id SERIAL PRIMARY KEY,
  kurz_id INTEGER NOT NULL REFERENCES kurzy(id) ON DELETE CASCADE,
  ucastnik_id INTEGER NOT NULL REFERENCES ucastnici(id) ON DELETE CASCADE,
  forma_kurzu forma_kurzu_enum DEFAULT 'prezencne' NOT NULL,
  pocet_ucastnikov INTEGER DEFAULT 1 NOT NULL,
  faktura_cislo VARCHAR(100),
  faktura_vystavena BOOLEAN DEFAULT FALSE NOT NULL,
  zaplatene BOOLEAN DEFAULT FALSE NOT NULL,
  stav stav_registracie_enum DEFAULT 'registrovany' NOT NULL,
  poznamka TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,
  updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL
);

CREATE UNIQUE INDEX IF NOT EXISTS registracie_kurz_ucastnik_idx ON registracie(kurz_id, ucastnik_id);

-- Create prilohy table (attachments)
CREATE TABLE IF NOT EXISTS prilohy (
  id SERIAL PRIMARY KEY,
  registracia_id INTEGER NOT NULL REFERENCES registracie(id) ON DELETE CASCADE,
  nazov_suboru VARCHAR(255) NOT NULL,
  typ_prilohy typ_prilohy_enum DEFAULT 'ine' NOT NULL,
  cesta_k_suboru VARCHAR(500) NOT NULL,
  mime_type VARCHAR(100),
  velkost_suboru BIGINT,
  popis TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,
  updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL
);

-- Create indexes for faster lookups
CREATE INDEX IF NOT EXISTS idx_registracie_kurz_id ON registracie(kurz_id);
CREATE INDEX IF NOT EXISTS idx_registracie_ucastnik_id ON registracie(ucastnik_id);
CREATE INDEX IF NOT EXISTS idx_prilohy_registracia_id ON prilohy(registracia_id);
