-- Migration 085: Solution Module & Timetracking Integration

-- 1. Create Solutions Table
CREATE TABLE IF NOT EXISTS sag_solutions (
    id SERIAL PRIMARY KEY,
    sag_id INTEGER NOT NULL REFERENCES sag_sager(id) ON DELETE CASCADE,
    title VARCHAR(255) NOT NULL,
    description TEXT,
    solution_type VARCHAR(50), -- Support, Drift, Konsulent, etc.
    result VARCHAR(50),        -- Løst, Delvist, Workaround, Ej løst
    created_by_user_id INTEGER, -- Reference to auth user (no FK to abstract 'users' table if not std)
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT uq_sag_solutions_sag_id UNIQUE (sag_id) -- 1:1 relation
);

-- 2. Update Timetracking Table to support Internal Cases & Solutions
ALTER TABLE tmodule_times ADD COLUMN IF NOT EXISTS solution_id INTEGER REFERENCES sag_solutions(id) ON DELETE SET NULL;
ALTER TABLE tmodule_times ADD COLUMN IF NOT EXISTS sag_id INTEGER REFERENCES sag_sager(id) ON DELETE SET NULL;

-- 3. Relax vTiger constraints to allow manual creation in Hub
ALTER TABLE tmodule_times ALTER COLUMN vtiger_id DROP NOT NULL;
ALTER TABLE tmodule_times ALTER COLUMN case_id DROP NOT NULL;

-- 4. Indexes for performance
CREATE INDEX IF NOT EXISTS idx_sag_solutions_sag_id ON sag_solutions(sag_id);
CREATE INDEX IF NOT EXISTS idx_tmodule_times_solution_id ON tmodule_times(solution_id);
CREATE INDEX IF NOT EXISTS idx_tmodule_times_sag_id ON tmodule_times(sag_id);
