-- ============================================================================
-- Schema: trading
-- File: 13-drawing_templates.sql
-- Description: Reusable drawing templates and presets
-- Related: OQI-003 Trading Charts, GAP-006
-- Dependencies: 00-enums.sql, auth.users
-- ============================================================================

CREATE TABLE IF NOT EXISTS trading.drawing_templates (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE, -- NULL = system template
    name VARCHAR(100) NOT NULL,
    description TEXT,
    tool_type trading.drawing_tool_type NOT NULL,
    style JSONB NOT NULL,
    fib_levels DECIMAL(5,4)[] DEFAULT NULL,
    is_system BOOLEAN NOT NULL DEFAULT false,
    is_public BOOLEAN NOT NULL DEFAULT false,
    usage_count INTEGER NOT NULL DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    CONSTRAINT drawing_templates_name_not_empty CHECK (length(trim(name)) > 0)
);

-- Indexes
CREATE INDEX idx_drawing_templates_user ON trading.drawing_templates(user_id);
CREATE INDEX idx_drawing_templates_tool_type ON trading.drawing_templates(tool_type);
CREATE INDEX idx_drawing_templates_public ON trading.drawing_templates(is_public) WHERE is_public = true;
CREATE INDEX idx_drawing_templates_system ON trading.drawing_templates(is_system) WHERE is_system = true;

-- Trigger
CREATE TRIGGER trg_drawing_templates_updated_at
    BEFORE UPDATE ON trading.drawing_templates
    FOR EACH ROW
    EXECUTE FUNCTION public.update_updated_at();

-- Comments
COMMENT ON TABLE trading.drawing_templates IS 'Reusable drawing templates and presets for chart annotations';
COMMENT ON COLUMN trading.drawing_templates.user_id IS 'Owner of template, NULL for system templates';
COMMENT ON COLUMN trading.drawing_templates.style IS 'Default style configuration for the template';
COMMENT ON COLUMN trading.drawing_templates.fib_levels IS 'Default Fibonacci levels for retracement/extension templates';
COMMENT ON COLUMN trading.drawing_templates.is_system IS 'System-provided template (cannot be deleted by users)';
COMMENT ON COLUMN trading.drawing_templates.is_public IS 'Template is visible to all users';
COMMENT ON COLUMN trading.drawing_templates.usage_count IS 'Number of times this template has been applied';
