-- Migration: Initial schema for Sag Module

-- Main table for cases
CREATE TABLE IF NOT EXISTS sag_sager (
    id SERIAL PRIMARY KEY,
    titel VARCHAR NOT NULL,
    beskrivelse TEXT,
    template_key VARCHAR,
    status VARCHAR NOT NULL DEFAULT 'åben' CHECK (status IN ('åben', 'lukket')),
    customer_id INTEGER,
    ansvarlig_bruger_id INTEGER,
    created_by_user_id INTEGER NOT NULL,
    deadline TIMESTAMP,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMP
);

-- 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 NOT NULL,
    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,
    state VARCHAR DEFAULT 'open' CHECK (state IN ('open', 'closed')),
    closed_at TIMESTAMP,
    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_created_by ON sag_sager(created_by_user_id) 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();