-- Table pour les bannières du carousel (gérée par super admin)
CREATE TABLE IF NOT EXISTS banners (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  image_url TEXT NOT NULL,
  link_url TEXT,
  title TEXT,
  "order" INTEGER DEFAULT 0,
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Table pour les super admins
CREATE TABLE IF NOT EXISTS admins (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Table pour les signatures des utilisateurs
CREATE TABLE IF NOT EXISTS user_signatures (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE UNIQUE,
  email TEXT,
  first_name TEXT,
  last_name TEXT,
  job_title TEXT,
  company TEXT,
  phone TEXT,
  mobile TEXT,
  website TEXT,
  address TEXT,
  photo_url TEXT,
  logo_url TEXT,
  linkedin TEXT,
  twitter TEXT,
  facebook TEXT,
  instagram TEXT,
  primary_color TEXT DEFAULT '#3498db',
  secondary_color TEXT DEFAULT '#2c3e50',
  accent_color TEXT DEFAULT '#5dade2',
  photo_shape TEXT DEFAULT 'hexagon',
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Index pour optimiser les requêtes
CREATE INDEX IF NOT EXISTS idx_banners_active ON banners(is_active, "order");
CREATE INDEX IF NOT EXISTS idx_admins_user_id ON admins(user_id);
CREATE INDEX IF NOT EXISTS idx_user_signatures_user_id ON user_signatures(user_id);

-- Fonction pour mettre à jour updated_at automatiquement
CREATE OR REPLACE FUNCTION update_updated_at()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Trigger pour mettre à jour updated_at sur banners
DROP TRIGGER IF EXISTS banners_updated_at ON banners;
CREATE TRIGGER banners_updated_at
  BEFORE UPDATE ON banners
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at();

-- Trigger pour mettre à jour updated_at sur user_signatures
DROP TRIGGER IF EXISTS user_signatures_updated_at ON user_signatures;
CREATE TRIGGER user_signatures_updated_at
  BEFORE UPDATE ON user_signatures
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at();

-- RLS (Row Level Security)
ALTER TABLE banners ENABLE ROW LEVEL SECURITY;
ALTER TABLE admins ENABLE ROW LEVEL SECURITY;
ALTER TABLE user_signatures ENABLE ROW LEVEL SECURITY;

-- Politique: Tout le monde peut lire les bannières actives
CREATE POLICY "Bannières actives visibles par tous" ON banners
  FOR SELECT USING (is_active = true);

-- Politique: Les admins peuvent TOUT lire (même inactives)
CREATE POLICY "Admins peuvent tout lire" ON banners
  FOR SELECT USING (
    EXISTS (
      SELECT 1 FROM admins WHERE user_id = auth.uid()
    )
  );

-- Politique: Les admins peuvent insérer
CREATE POLICY "Admins peuvent inserer" ON banners
  FOR INSERT WITH CHECK (
    EXISTS (
      SELECT 1 FROM admins WHERE user_id = auth.uid()
    )
  );

-- Politique: Les admins peuvent modifier
CREATE POLICY "Admins peuvent modifier" ON banners
  FOR UPDATE USING (
    EXISTS (
      SELECT 1 FROM admins WHERE user_id = auth.uid()
    )
  );

-- Politique: Les admins peuvent supprimer
CREATE POLICY "Admins peuvent supprimer" ON banners
  FOR DELETE USING (
    EXISTS (
      SELECT 1 FROM admins WHERE user_id = auth.uid()
    )
  );

-- Politique: Un utilisateur peut vérifier s'il est admin (lecture de sa propre entrée)
CREATE POLICY "Users peuvent verifier leur statut admin" ON admins
  FOR SELECT USING (user_id = auth.uid());

-- ==========================================
-- POLITIQUES POUR user_signatures
-- ==========================================

-- Utilisateurs peuvent lire leur propre signature
CREATE POLICY "Users peuvent lire leur signature" ON user_signatures
  FOR SELECT USING (user_id = auth.uid());

-- Utilisateurs peuvent créer leur propre signature
CREATE POLICY "Users peuvent creer leur signature" ON user_signatures
  FOR INSERT WITH CHECK (user_id = auth.uid());

-- Utilisateurs peuvent modifier leur propre signature
CREATE POLICY "Users peuvent modifier leur signature" ON user_signatures
  FOR UPDATE USING (user_id = auth.uid());

-- Admins peuvent lire TOUTES les signatures
CREATE POLICY "Admins peuvent lire toutes signatures" ON user_signatures
  FOR SELECT USING (
    EXISTS (SELECT 1 FROM admins WHERE user_id = auth.uid())
  );

-- Admins peuvent modifier TOUTES les signatures
CREATE POLICY "Admins peuvent modifier toutes signatures" ON user_signatures
  FOR UPDATE USING (
    EXISTS (SELECT 1 FROM admins WHERE user_id = auth.uid())
  );

-- Admins peuvent créer des signatures pour n'importe qui
CREATE POLICY "Admins peuvent creer signatures" ON user_signatures
  FOR INSERT WITH CHECK (
    EXISTS (SELECT 1 FROM admins WHERE user_id = auth.uid())
  );

-- Admins peuvent supprimer des signatures
CREATE POLICY "Admins peuvent supprimer signatures" ON user_signatures
  FOR DELETE USING (
    EXISTS (SELECT 1 FROM admins WHERE user_id = auth.uid())
  );

-- Insérer l'admin principal
INSERT INTO admins (user_id, email) VALUES
  ('27f80c55-f045-4e6c-9751-56f5c86b71a2', 'admin@navier.net')
ON CONFLICT (email) DO NOTHING;

-- Insérer quelques bannières par défaut (à personnaliser)
INSERT INTO banners (image_url, link_url, title, "order", is_active) VALUES
  ('https://via.placeholder.com/600x150/3498db/ffffff?text=Promotion+1', 'https://example.com/promo1', 'Promotion 1', 1, true),
  ('https://via.placeholder.com/600x150/e74c3c/ffffff?text=Promotion+2', 'https://example.com/promo2', 'Promotion 2', 2, true),
  ('https://via.placeholder.com/600x150/2ecc71/ffffff?text=Promotion+3', 'https://example.com/promo3', 'Promotion 3', 3, true)
ON CONFLICT DO NOTHING;
