-- Water Management System Database Initialization

-- Create database if not exists
CREATE DATABASE IF NOT EXISTS water_management;

-- Connect to the database
\c water_management;

-- Create user with permissions
DO $$
BEGIN
    IF NOT EXISTS (SELECT FROM pg_user WHERE usename = 'water_user') THEN
        CREATE USER water_user WITH PASSWORD 'water_pass';
    END IF;
END
$$;

-- Grant permissions
GRANT ALL PRIVILEGES ON DATABASE water_management TO water_user;

-- Grant all privileges on all tables in the public schema
GRANT ALL ON ALL TABLES IN SCHEMA public TO water_user;
GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO water_user;
GRANT ALL ON ALL FUNCTIONS IN SCHEMA public TO water_user;

-- Create PostGIS extension for spatial data
CREATE EXTENSION IF NOT EXISTS postgis;

-- Create IoT schema
CREATE SCHEMA IF NOT EXISTS iot;

-- Set default schema to iot
SET search_path TO iot, public;

-- Create device models table
CREATE TABLE IF NOT EXISTS iot_device_models (
    id BIGSERIAL PRIMARY KEY,
    model_code VARCHAR(100) NOT NULL UNIQUE,
    model_name VARCHAR(200) NOT NULL,
    device_type VARCHAR(50) NOT NULL,
    protocol VARCHAR(50) NOT NULL,
    description TEXT,
    is_active BOOLEAN NOT NULL DEFAULT true,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Create device instances table
CREATE TABLE IF NOT EXISTS iot_device_instances (
    id BIGSERIAL PRIMARY KEY,
    device_id VARCHAR(100) NOT NULL UNIQUE,
    device_model_id BIGINT NOT NULL REFERENCES iot_device_models(id),
    name VARCHAR(200) NOT NULL,
    location VARCHAR(500),
    is_active BOOLEAN NOT NULL DEFAULT true,
    last_seen_at TIMESTAMP,
    registered_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    device_info JSONB,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Create device shadows table
CREATE TABLE IF NOT EXISTS iot_device_shadows (
    id BIGSERIAL PRIMARY KEY,
    device_id BIGINT NOT NULL REFERENCES iot_device_instances(id),
    shadow_state JSONB NOT NULL DEFAULT '{}',
    desired_state JSONB DEFAULT '{}',
    reported_state JSONB DEFAULT '{}',
    version BIGINT NOT NULL DEFAULT 1,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(device_id)
);

-- Create telemetry data table
CREATE TABLE IF NOT EXISTS iot_telemetry (
    id BIGSERIAL PRIMARY KEY,
    device_id VARCHAR(100) NOT NULL,
    timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    telemetry_data JSONB NOT NULL,
    device_model_id BIGINT REFERENCES iot_device_models(id),
    processed BOOLEAN NOT NULL DEFAULT false,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Create index for better performance
CREATE INDEX IF NOT EXISTS idx_device_instances_device_id ON iot_device_instances(device_id);
CREATE INDEX IF NOT EXISTS idx_device_instances_model_id ON iot_device_instances(device_model_id);
CREATE INDEX IF NOT EXISTS idx_device_shadows_device_id ON iot_device_shadows(device_id);
CREATE INDEX IF NOT EXISTS idx_telemetry_device_id ON iot_telemetry(device_id);
CREATE INDEX IF NOT EXISTS idx_telemetry_timestamp ON iot_telemetry(timestamp);

-- Insert sample device models
INSERT INTO iot_device_models (model_code, model_name, device_type, protocol, description, is_active)
VALUES 
    ('TEMP-001', 'Temperature Sensor', 'temperature', 'modbus', 'Temperature monitoring sensor', true),
    ('PRESSURE-001', 'Pressure Sensor', 'pressure', 'modbus', 'Pressure monitoring sensor', true),
    ('FLOW-001', 'Flow Meter', 'flow', 'modbus', 'Water flow measurement', true)
ON CONFLICT (model_code) DO NOTHING;

-- Insert sample device instances
INSERT INTO iot_device_instances (device_id, device_model_id, name, location, is_active, device_info)
VALUES 
    ('TEMP-001-001', 1, 'Main Temperature Sensor', 'Main Pump Room', true, '{"installation_date": "2026-01-15", "calibration_date": "2026-06-01"}'),
    ('PRESSURE-001-001', 2, 'Main Pressure Sensor', 'Distribution Center', true, '{"installation_date": "2026-01-15", "calibration_date": "2026-06-01"}')
ON CONFLICT (device_id) DO NOTHING;

-- Create spatial table for device locations if needed
CREATE TABLE IF NOT EXISTS iot_device_locations (
    id BIGSERIAL PRIMARY KEY,
    device_id VARCHAR(100) NOT NULL UNIQUE,
    location_name VARCHAR(200) NOT NULL,
    coordinates GEOMETRY(POINT, 4326),
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Insert sample spatial data
INSERT INTO iot_device_locations (device_id, location_name, coordinates)
VALUES 
    ('TEMP-001-001', 'Main Pump Room', ST_MakePoint(44.2614, 84.2936)),
    ('PRESSURE-001-001', 'Distribution Center', ST_MakePoint(44.2605, 84.2942))
ON CONFLICT (device_id) DO NOTHING;

-- Grant permissions on all tables in iot schema
GRANT ALL ON ALL TABLES IN SCHEMA iot TO water_user;
GRANT ALL ON ALL SEQUENCES IN SCHEMA iot TO water_user;
GRANT ALL ON ALL FUNCTIONS IN SCHEMA iot TO water_user;

-- Refresh materialized views if any
-- REFRESH MATERIALIZED VIEW IF EXISTS iot_device_summary;