-- Sag Module: Initialize case management tables
-- Supports universal case handling with relations and tags

-- Main cases table
CREATE TABLE IF NOT EXISTS sag_sager (
    id SERIAL PRIMARY KEY,
    titel VARCHAR(255) NOT NULL,
    beskrivelse TEXT,
    type VARCHAR(50) NOT NULL DEFAULT 'ticket', -- ticket, opgave, ordre, etc.
    status VARCHAR(50) NOT NULL DEFAULT 'åben', -- åben, i_gang, afsluttet, on_hold
    customer_id INTEGER NOT NULL REFERENCES customers(id),
    ansvarlig_bruger_id INTEGER,
    deadline TIMESTAMP,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMP,
    CONSTRAINT valid_status CHECK (status IN ('åben', 'i_gang', 'afsluttet', 'on_hold'))
);

-- Relations between cases
CREATE TABLE IF NOT EXISTS sag_relationer (
    id SERIAL PRIMARY KEY,
    kilde_sag_id INTEGER NOT NULL REFERENCES sag_sager(id) ON DELETE CASCADE,
    målsag_id INTEGER NOT NULL REFERENCES sag_sager(id) ON DELETE CASCADE,
    relationstype VARCHAR(50) NOT NULL, -- forælder, barn, afledt_af, blokkerer, udfører_for
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMP,
    CONSTRAINT different_cases CHECK (kilde_sag_id != målsag_id)
);

-- Tags for categorization
CREATE TABLE IF NOT EXISTS sag_tags (
    id SERIAL PRIMARY KEY,
    sag_id INTEGER NOT NULL REFERENCES sag_sager(id) ON DELETE CASCADE,
    tag_navn VARCHAR(100) NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMP
);

-- Indexes for performance
CREATE INDEX IF NOT EXISTS idx_sag_sager_customer_id ON sag_sager(customer_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_sag_sager_status ON sag_sager(status) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_sag_sager_ansvarlig ON sag_sager(ansvarlig_bruger_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_sag_relationer_kilde ON sag_relationer(kilde_sag_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_sag_relationer_mål ON sag_relationer(målsag_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_sag_tags_sag_id ON sag_tags(sag_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_sag_tags_tag_navn ON sag_tags(tag_navn) WHERE deleted_at IS NULL;

-- Trigger to auto-update updated_at
CREATE OR REPLACE FUNCTION update_sag_sager_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trigger_sag_sager_updated_at ON sag_sager;
CREATE TRIGGER trigger_sag_sager_updated_at
BEFORE UPDATE ON sag_sager
FOR EACH ROW
EXECUTE FUNCTION update_sag_sager_updated_at();
