-- Create contract_type_templates table for user-defined contract templates
CREATE TABLE contract_type_templates (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    owner_id UUID NOT NULL REFERENCES owners(id) ON DELETE CASCADE,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    phases JSONB NOT NULL,           -- [{id, name, order}]
    default_phase VARCHAR(64) NOT NULL,
    deliverables JSONB,              -- {phase_id: [{id, name, priority}]}
    version INTEGER NOT NULL DEFAULT 1,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT unique_template_name_per_owner UNIQUE (owner_id, name)
);

CREATE INDEX idx_contract_type_templates_owner_id ON contract_type_templates(owner_id);

-- Add phase_config column to contracts (stores copied template config at creation time)
ALTER TABLE contracts ADD COLUMN IF NOT EXISTS phase_config JSONB;
