-- Migration 092: Tag groups and behaviors

CREATE TABLE IF NOT EXISTS tag_groups (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) UNIQUE NOT NULL,
    description TEXT,
    behavior VARCHAR(20) NOT NULL DEFAULT 'multi', -- multi, single, toggle
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name = 'tags' AND column_name = 'tag_group_id'
    ) THEN
        ALTER TABLE tags ADD COLUMN tag_group_id INTEGER REFERENCES tag_groups(id) ON DELETE SET NULL;
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_tags_group ON tags(tag_group_id);

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

DROP TRIGGER IF EXISTS update_tag_groups_updated_at ON tag_groups;
CREATE TRIGGER update_tag_groups_updated_at
    BEFORE UPDATE ON tag_groups
    FOR EACH ROW
    EXECUTE FUNCTION update_tag_groups_updated_at();

-- Seed tag groups
INSERT INTO tag_groups (name, description, behavior) VALUES
('View', 'Styrer visning/layout', 'toggle'),
('Status', 'Sag status', 'toggle')
ON CONFLICT (name) DO NOTHING;

-- Seed view tags
INSERT INTO tags (name, type, description, color, tag_group_id)
SELECT v.name, 'category', v.description, v.color, tg.id
FROM (
    VALUES
        ('Pipeline', 'Pipeline view', '#0f4c75'),
        ('Kundevisning', 'Kundevisning view', '#0f4c75'),
        ('Sag-detalje', 'Sag-detalje view', '#0f4c75')
) AS v(name, description, color)
JOIN tag_groups tg ON tg.name = 'View'
ON CONFLICT (name, type) DO NOTHING;
