-- Unified projects, assets linking, UI preferences (layout + viz modes)

CREATE TABLE IF NOT EXISTS cockpit_projects (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    client_id INTEGER REFERENCES clients(id) ON DELETE SET NULL,
    description TEXT,
    status VARCHAR(32) DEFAULT 'active',
    created_by VARCHAR(64) DEFAULT 'ceo',
    metadata JSONB DEFAULT '{}'::jsonb,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_cockpit_projects_client ON cockpit_projects(client_id);
CREATE INDEX IF NOT EXISTS idx_cockpit_projects_status ON cockpit_projects(status, updated_at DESC);

CREATE TABLE IF NOT EXISTS project_assets (
    id SERIAL PRIMARY KEY,
    project_id INTEGER NOT NULL REFERENCES cockpit_projects(id) ON DELETE CASCADE,
    asset_type VARCHAR(64) NOT NULL,
    ref_id VARCHAR(128),
    title VARCHAR(255),
    file_path TEXT,
    payload JSONB DEFAULT '{}'::jsonb,
    created_by VARCHAR(64) DEFAULT 'ceo',
    source_agent VARCHAR(64),
    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_project_assets_project ON project_assets(project_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_project_assets_type ON project_assets(asset_type, ref_id);

CREATE TABLE IF NOT EXISTS packaging_outputs (
    id VARCHAR(64) PRIMARY KEY,
    project_id INTEGER REFERENCES cockpit_projects(id) ON DELETE SET NULL,
    spec JSONB NOT NULL,
    svg TEXT NOT NULL,
    created_by VARCHAR(64) DEFAULT 'packaging',
    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS user_ui_preferences (
    user_key VARCHAR(64) PRIMARY KEY DEFAULT 'ceo',
    dashboard_layout JSONB DEFAULT '[]'::jsonb,
    viz_modes JSONB DEFAULT '{}'::jsonb,
    global_viz_mode VARCHAR(32) DEFAULT 'neo-bars',
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

INSERT INTO user_ui_preferences (user_key, dashboard_layout, global_viz_mode) VALUES
('ceo', '["kpis","executive","briefing","retail","analytics","approvals","feed"]'::jsonb, 'neo-bars')
ON CONFLICT (user_key) DO NOTHING;

ALTER TABLE photo_imports ADD COLUMN IF NOT EXISTS project_id INTEGER REFERENCES cockpit_projects(id) ON DELETE SET NULL;
ALTER TABLE photo_imports ADD COLUMN IF NOT EXISTS created_by VARCHAR(64) DEFAULT 'ceo';
