-- name: InitializeSchema :exec
CREATE TABLE IF NOT EXISTS content (
    id TEXT NOT NULL,
    site_id TEXT NOT NULL,
    html_content TEXT NOT NULL,
    original_template TEXT,
    type TEXT NOT NULL CHECK (type IN ('text', 'link')),
    created_at BIGINT DEFAULT (EXTRACT(EPOCH FROM NOW())) NOT NULL,
    updated_at BIGINT DEFAULT (EXTRACT(EPOCH FROM NOW())) NOT NULL,
    last_edited_by TEXT DEFAULT 'system' NOT NULL,
    PRIMARY KEY (id, site_id)
);

-- name: InitializeVersionsTable :exec
CREATE TABLE IF NOT EXISTS content_versions (
    version_id SERIAL PRIMARY KEY,
    content_id TEXT NOT NULL,
    site_id TEXT NOT NULL,
    html_content TEXT NOT NULL,
    original_template TEXT,
    type TEXT NOT NULL,
    created_at BIGINT DEFAULT (EXTRACT(EPOCH FROM NOW())) NOT NULL,
    created_by TEXT DEFAULT 'system' NOT NULL
);

-- name: CreateContentSiteIndex :exec
CREATE INDEX IF NOT EXISTS idx_content_site_id ON content(site_id);

-- name: CreateContentUpdatedAtIndex :exec
CREATE INDEX IF NOT EXISTS idx_content_updated_at ON content(updated_at);

-- name: CreateVersionsLookupIndex :exec
CREATE INDEX IF NOT EXISTS idx_content_versions_lookup ON content_versions(content_id, site_id, created_at DESC);

-- name: CreateUpdateFunction :exec
CREATE OR REPLACE FUNCTION update_content_timestamp()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = EXTRACT(EPOCH FROM NOW());
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- name: CreateUpdateTrigger :exec
DROP TRIGGER IF EXISTS update_content_updated_at ON content;
CREATE TRIGGER update_content_updated_at
BEFORE UPDATE ON content
FOR EACH ROW
EXECUTE FUNCTION update_content_timestamp();