-- 1) Create a dedicated user
DO
$$
BEGIN
   IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'ssap_user') THEN
      CREATE ROLE ssap_user WITH
        LOGIN
        PASSWORD 'ssap_pass'
        NOSUPERUSER
        NOCREATEDB
        NOCREATEROLE
        NOINHERIT;
   END IF;
END
$$;

-- 2) Create a dedicated database
DO
$$
BEGIN
   IF NOT EXISTS (SELECT FROM pg_database WHERE datname = 'ssap') THEN
      CREATE DATABASE ssap OWNER ssap_user;
   END IF;
END
$$;

-- 3) Connect to the DB (run separately if using psql)
-- \c ssap

-- 4) Lock down default public privileges (recommended)
REVOKE ALL ON DATABASE ssap FROM PUBLIC;
GRANT CONNECT ON DATABASE ssap TO ssap_user;

-- 5) Ensure schema permissions
GRANT USAGE, CREATE ON SCHEMA public TO ssap_user;

-- 6) Ensure ownership & permissions for future objects
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT ALL ON TABLES TO ssap_user;

ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT ALL ON SEQUENCES TO ssap_user;

ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT ALL ON FUNCTIONS TO ssap_user;


CREATE TABLE IF NOT EXISTS device_registrations (
  id BIGSERIAL PRIMARY KEY,
  device_registration_id VARCHAR(50) UNIQUE NOT NULL,
  name VARCHAR(100) NOT NULL,
  mobile VARCHAR(20) NOT NULL,
  device_model VARCHAR(100),
  manufacturer VARCHAR(100),
  os VARCHAR(50),
  os_version VARCHAR(50),
  device_id VARCHAR(100),
  app_version VARCHAR(30),
  created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
CREATE TABLE IF NOT EXISTS sessions (
  id BIGSERIAL PRIMARY KEY,
  session_id VARCHAR(50) UNIQUE NOT NULL,
  device_registration_id VARCHAR(50) NOT NULL REFERENCES device_registrations(device_registration_id),
  latitude DECIMAL(10, 8),
  longitude DECIMAL(11, 8),
  connectivity_type VARCHAR(20) NOT NULL,
  wifi_bssid VARCHAR(50),
  created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_sessions_device_reg_id ON sessions(device_registration_id);
CREATE INDEX IF NOT EXISTS idx_sessions_created_at ON sessions(created_at);
