-- V029 Commercial Platform & Customer Success
-- Tables are also created by SQLAlchemy Base.metadata.create_all in native mode.
CREATE INDEX IF NOT EXISTS ix_commercial_leads_v029_status ON commercial_leads_v029(status);
CREATE INDEX IF NOT EXISTS ix_commercial_opportunities_v029_stage ON commercial_opportunities_v029(stage);
CREATE INDEX IF NOT EXISTS ix_support_tickets_v029_tenant_status ON support_tickets_v029(tenant_id,status);
CREATE INDEX IF NOT EXISTS ix_customer_health_v029_tenant_date ON customer_health_snapshots_v029(tenant_id,calculated_at);

ALTER TABLE support_tickets_v029 ENABLE ROW LEVEL SECURITY;
ALTER TABLE support_ticket_messages_v029 ENABLE ROW LEVEL SECURITY;
ALTER TABLE customer_payment_methods_v029 ENABLE ROW LEVEL SECURITY;
ALTER TABLE customer_health_snapshots_v029 ENABLE ROW LEVEL SECURITY;
ALTER TABLE customer_success_plans_v029 ENABLE ROW LEVEL SECURITY;
ALTER TABLE nps_survey_responses_v029 ENABLE ROW LEVEL SECURITY;

DROP POLICY IF EXISTS tenant_support_tickets_v029 ON support_tickets_v029;
CREATE POLICY tenant_support_tickets_v029 ON support_tickets_v029
USING (tenant_id::text=current_setting('app.current_tenant_id',true))
WITH CHECK (tenant_id::text=current_setting('app.current_tenant_id',true));
DROP POLICY IF EXISTS tenant_support_messages_v029 ON support_ticket_messages_v029;
CREATE POLICY tenant_support_messages_v029 ON support_ticket_messages_v029
USING (tenant_id::text=current_setting('app.current_tenant_id',true))
WITH CHECK (tenant_id::text=current_setting('app.current_tenant_id',true));
DROP POLICY IF EXISTS tenant_payment_methods_v029 ON customer_payment_methods_v029;
CREATE POLICY tenant_payment_methods_v029 ON customer_payment_methods_v029
USING (tenant_id::text=current_setting('app.current_tenant_id',true))
WITH CHECK (tenant_id::text=current_setting('app.current_tenant_id',true));
DROP POLICY IF EXISTS tenant_health_v029 ON customer_health_snapshots_v029;
CREATE POLICY tenant_health_v029 ON customer_health_snapshots_v029
USING (tenant_id::text=current_setting('app.current_tenant_id',true))
WITH CHECK (tenant_id::text=current_setting('app.current_tenant_id',true));
DROP POLICY IF EXISTS tenant_success_plans_v029 ON customer_success_plans_v029;
CREATE POLICY tenant_success_plans_v029 ON customer_success_plans_v029
USING (tenant_id::text=current_setting('app.current_tenant_id',true))
WITH CHECK (tenant_id::text=current_setting('app.current_tenant_id',true));
DROP POLICY IF EXISTS tenant_nps_v029 ON nps_survey_responses_v029;
CREATE POLICY tenant_nps_v029 ON nps_survey_responses_v029
USING (tenant_id::text=current_setting('app.current_tenant_id',true))
WITH CHECK (tenant_id::text=current_setting('app.current_tenant_id',true));
