-- Migration 144: Extend tags with brand/type classes and catch words

-- Add catch words storage for tag suggestion matching
ALTER TABLE tags
ADD COLUMN IF NOT EXISTS catch_words_json JSONB NOT NULL DEFAULT '[]'::jsonb;

-- Extend allowed tag types to include brand and type
DO $$
DECLARE
    constraint_name text;
BEGIN
    ALTER TABLE tags DROP CONSTRAINT IF EXISTS tags_type_check;

    FOR constraint_name IN
        SELECT con.conname
        FROM pg_constraint con
        JOIN pg_class rel ON rel.oid = con.conrelid
        WHERE rel.relname = 'tags'
          AND con.contype = 'c'
          AND pg_get_constraintdef(con.oid) ILIKE '%type IN (%'
    LOOP
        EXECUTE format('ALTER TABLE tags DROP CONSTRAINT %I', constraint_name);
    END LOOP;
END $$;

ALTER TABLE tags
ADD CONSTRAINT tags_type_check
CHECK (type IN ('workflow', 'status', 'category', 'priority', 'billing', 'brand', 'type'));

-- Seed a couple of starter tags for the new classes
INSERT INTO tags (name, type, description, color, icon, is_active, catch_words_json)
VALUES
    ('Microsoft', 'brand', 'Brand tag for Microsoft related cases', '#006d77', 'bi-microsoft', true, '["microsoft","ms 365","office 365","azure"]'::jsonb),
    ('Adobe', 'brand', 'Brand tag for Adobe related cases', '#006d77', 'bi-box', true, '["adobe","acrobat","creative cloud"]'::jsonb),
    ('Printer', 'type', 'Type tag for printer related work', '#5c677d', 'bi-printer', true, '["printer","toner","print","scanner"]'::jsonb),
    ('Email', 'type', 'Type tag for mail related work', '#5c677d', 'bi-envelope', true, '["mail","email","outlook","smtp","imap"]'::jsonb)
ON CONFLICT (name, type) DO NOTHING;

COMMENT ON COLUMN tags.catch_words_json IS 'JSON array of catch words used for automated tag suggestions';
