-- Migration : Table pour les rapports CSP
-- Date : 14 novembre 2025
-- Description : Stockage des violations CSP pour analyse de sécurité

-- Table principale pour les rapports CSP
CREATE TABLE IF NOT EXISTS csp_reports (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  document_uri TEXT NOT NULL,
  violated_directive TEXT NOT NULL,
  effective_directive TEXT,
  blocked_uri TEXT,
  source_file TEXT,
  line_number INTEGER,
  column_number INTEGER,
  status_code INTEGER,
  user_agent TEXT,
  referrer TEXT,
  original_policy TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Index pour les requêtes fréquentes
CREATE INDEX idx_csp_reports_created_at ON csp_reports(created_at DESC);
CREATE INDEX idx_csp_reports_directive ON csp_reports(violated_directive);
CREATE INDEX idx_csp_reports_blocked_uri ON csp_reports(blocked_uri);
CREATE INDEX idx_csp_reports_document_uri ON csp_reports(document_uri);

-- Table pour tracker les emails envoyés (éviter les doublons)
CREATE TABLE IF NOT EXISTS csp_email_logs (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  report_date DATE NOT NULL UNIQUE,
  reports_count INTEGER NOT NULL DEFAULT 0,
  unique_violations INTEGER NOT NULL DEFAULT 0,
  email_sent_at TIMESTAMPTZ DEFAULT NOW()
);

-- Activer RLS (même si non utilisé pour l'instant)
ALTER TABLE csp_reports ENABLE ROW LEVEL SECURITY;
ALTER TABLE csp_email_logs ENABLE ROW LEVEL SECURITY;

-- Politique pour permettre l'insertion via service role
CREATE POLICY "Service role can insert reports" ON csp_reports
  FOR INSERT
  WITH CHECK (true);

CREATE POLICY "Staff can view reports" ON csp_reports
  FOR SELECT
  USING (
    EXISTS (
      SELECT 1 FROM staff_users 
      WHERE staff_users.user_id = auth.uid() 
      AND staff_users.is_staff = true
    )
  );

-- Vue pour les statistiques
CREATE OR REPLACE VIEW csp_reports_summary AS
SELECT 
  violated_directive,
  COUNT(*) as violation_count,
  COUNT(DISTINCT blocked_uri) as unique_blocked_uris,
  COUNT(DISTINCT document_uri) as affected_pages,
  MAX(created_at) as last_occurrence
FROM csp_reports
WHERE created_at > NOW() - INTERVAL '7 days'
GROUP BY violated_directive
ORDER BY violation_count DESC;

-- Grant permissions
GRANT SELECT ON csp_reports_summary TO authenticated;

-- Commentaires
COMMENT ON TABLE csp_reports IS 'Stockage des violations CSP (Content Security Policy) pour analyse de sécurité';
COMMENT ON TABLE csp_email_logs IS 'Log des emails quotidiens envoyés avec rapports CSP';
COMMENT ON VIEW csp_reports_summary IS 'Vue résumée des violations CSP des 7 derniers jours';
