/*
  # Create users table with indexes

  1. New Tables
    - `users`
      - `id` (uuid, primary key)
      - `phone_number` (text, unique)
      - `username` (text)
      - `email` (text)
      - `address` (text)
      - `profile_picture` (text)
      - `created_at` (timestamptz)

  2. Indexes
    - Index on phone_number for fast lookups
    - Index on email for future queries
    
  3. Security
    - Enable RLS
    - Add policies for authenticated users
*/

CREATE TABLE IF NOT EXISTS users (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  phone_number text UNIQUE NOT NULL,
  username text,
  email text,
  address text,
  profile_picture text,
  created_at timestamptz DEFAULT now()
);

-- Create indexes for better performance
CREATE INDEX IF NOT EXISTS users_phone_number_idx ON users(phone_number);
CREATE INDEX IF NOT EXISTS users_email_idx ON users(email);

-- Enable Row Level Security
ALTER TABLE users ENABLE ROW LEVEL SECURITY;

-- Create policies
CREATE POLICY "Users can read all users"
  ON users
  FOR SELECT
  TO authenticated
  USING (true);

CREATE POLICY "Users can update their own data"
  ON users
  FOR UPDATE
  TO authenticated
  USING (auth.uid() = id);

CREATE POLICY "Users can insert their own data"
  ON users
  FOR INSERT
  TO authenticated
  WITH CHECK (auth.uid() = id);

-- Insert sample data
INSERT INTO users (id, phone_number, username, email, address, profile_picture)
VALUES 
  (gen_random_uuid(), '+1234567890', 'John Doe', 'john@example.com', '123 Main St, City, Country', 'uploads/default.jpg'),
  (gen_random_uuid(), '+1987654321', 'Jane Smith', 'jane@example.com', '456 Oak Ave, Town, Country', 'uploads/default.jpg'),
  (gen_random_uuid(), '+1122334455', 'Mike Johnson', 'mike@example.com', '789 Pine Rd, Village, Country', 'uploads/default.jpg')
ON CONFLICT (phone_number) DO NOTHING;