-- Location: supabase/migrations/20241019215951_sibu_transportation_system.sql
-- Schema Analysis: Fresh project with no existing database objects
-- Integration Type: Complete new schema for SIBU transportation system
-- Dependencies: New transportation management module

-- 1. Extensions & Custom Types
CREATE TYPE public.route_status AS ENUM ('active', 'inactive', 'maintenance');
CREATE TYPE public.stop_type AS ENUM ('terminal', 'regular', 'express_only');
CREATE TYPE public.bus_schedule_type AS ENUM ('weekday', 'weekend', 'holiday');

-- 2. Core Tables (no foreign keys)

-- Routes table - stores bus route information
CREATE TABLE public.routes (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name TEXT NOT NULL UNIQUE, -- e.g., "Boquete>David", "David>Boquete"
    description TEXT,
    origin_city TEXT NOT NULL,
    destination_city TEXT NOT NULL,
    distance_km DECIMAL(6,2),
    estimated_duration_minutes INTEGER,
    status public.route_status DEFAULT 'active'::public.route_status,
    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);

-- Bus stops table
CREATE TABLE public.bus_stops (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name TEXT NOT NULL,
    latitude DECIMAL(10,8) NOT NULL,
    longitude DECIMAL(11,8) NOT NULL,
    city TEXT NOT NULL,
    address TEXT,
    stop_type public.stop_type DEFAULT 'regular'::public.stop_type,
    has_shelter BOOLEAN DEFAULT false,
    has_seating BOOLEAN DEFAULT false,
    is_accessible BOOLEAN DEFAULT false,
    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);

-- 3. Dependent Tables (with foreign keys)

-- Route stops - junction table connecting routes to their stops
CREATE TABLE public.route_stops (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    route_id UUID REFERENCES public.routes(id) ON DELETE CASCADE,
    stop_id UUID REFERENCES public.bus_stops(id) ON DELETE CASCADE,
    stop_order INTEGER NOT NULL, -- Order of stop in the route (1, 2, 3...)
    travel_time_minutes INTEGER, -- Time from previous stop
    is_pickup_point BOOLEAN DEFAULT true,
    is_dropoff_point BOOLEAN DEFAULT true,
    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);

-- Bus schedules table
CREATE TABLE public.bus_schedules (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    route_id UUID REFERENCES public.routes(id) ON DELETE CASCADE,
    departure_time TIME NOT NULL,
    frequency_minutes INTEGER DEFAULT 30, -- How often bus runs (every 30 minutes)
    schedule_type public.bus_schedule_type DEFAULT 'weekday'::public.bus_schedule_type,
    is_active BOOLEAN DEFAULT true,
    notes TEXT,
    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);

-- Real-time bus tracking (for future implementation)
CREATE TABLE public.bus_tracking (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    route_id UUID REFERENCES public.routes(id) ON DELETE CASCADE,
    current_stop_id UUID REFERENCES public.bus_stops(id) ON DELETE SET NULL,
    next_stop_id UUID REFERENCES public.bus_stops(id) ON DELETE SET NULL,
    estimated_arrival_time TIMESTAMPTZ,
    delay_minutes INTEGER DEFAULT 0,
    bus_number TEXT,
    is_active BOOLEAN DEFAULT true,
    last_updated TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);

-- 4. Indexes for Performance
CREATE INDEX idx_routes_origin_destination ON public.routes(origin_city, destination_city);
CREATE INDEX idx_routes_status ON public.routes(status);
CREATE INDEX idx_bus_stops_city ON public.bus_stops(city);
CREATE INDEX idx_bus_stops_location ON public.bus_stops(latitude, longitude);
CREATE INDEX idx_route_stops_route_id ON public.route_stops(route_id);
CREATE INDEX idx_route_stops_stop_id ON public.route_stops(stop_id);
CREATE INDEX idx_route_stops_order ON public.route_stops(route_id, stop_order);
CREATE INDEX idx_bus_schedules_route_id ON public.bus_schedules(route_id);
CREATE INDEX idx_bus_schedules_departure_time ON public.bus_schedules(departure_time);
CREATE INDEX idx_bus_tracking_route_id ON public.bus_tracking(route_id);
CREATE INDEX idx_bus_tracking_active ON public.bus_tracking(is_active);

-- 5. Helper Functions (MUST BE BEFORE RLS POLICIES)
CREATE OR REPLACE FUNCTION public.calculate_next_bus_arrival(
    p_route_id UUID,
    p_stop_id UUID,
    p_current_time TIME DEFAULT CURRENT_TIME
)
RETURNS TABLE(
    next_departure TIME,
    estimated_arrival_time TIMESTAMPTZ,
    minutes_until_arrival INTEGER
)
LANGUAGE plpgsql
STABLE
SECURITY DEFINER
AS $$
DECLARE
    avg_speed_kmh DECIMAL := 65.0; -- Average bus speed
    stop_dwell_time INTEGER := 2; -- Minutes per stop
    route_distance DECIMAL;
    stop_position INTEGER;
    time_to_stop INTEGER;
    next_schedule_time TIME;
BEGIN
    -- Get the next scheduled departure
    SELECT bs.departure_time INTO next_schedule_time
    FROM public.bus_schedules bs
    WHERE bs.route_id = p_route_id
    AND bs.is_active = true
    AND bs.departure_time > p_current_time
    ORDER BY bs.departure_time ASC
    LIMIT 1;
    
    -- If no more schedules today, get first schedule tomorrow
    IF next_schedule_time IS NULL THEN
        SELECT bs.departure_time INTO next_schedule_time
        FROM public.bus_schedules bs
        WHERE bs.route_id = p_route_id
        AND bs.is_active = true
        ORDER BY bs.departure_time ASC
        LIMIT 1;
    END IF;
    
    -- Get stop position in route and calculate travel time
    SELECT rs.stop_order INTO stop_position
    FROM public.route_stops rs
    WHERE rs.route_id = p_route_id AND rs.stop_id = p_stop_id;
    
    -- Calculate estimated travel time to this stop (simplified calculation)
    time_to_stop := (stop_position - 1) * stop_dwell_time + (stop_position * 3); -- ~3 min between stops
    
    RETURN QUERY SELECT
        next_schedule_time,
        (CURRENT_DATE + next_schedule_time + (time_to_stop || ' minutes')::INTERVAL)::TIMESTAMPTZ,
        EXTRACT(EPOCH FROM (
            (CURRENT_DATE + next_schedule_time + (time_to_stop || ' minutes')::INTERVAL) - NOW()
        ))::INTEGER / 60;
END;
$$;

CREATE OR REPLACE FUNCTION public.get_route_stops_ordered(p_route_id UUID)
RETURNS TABLE(
    stop_id UUID,
    stop_name TEXT,
    latitude DECIMAL,
    longitude DECIMAL,
    stop_order INTEGER,
    travel_time_minutes INTEGER
)
LANGUAGE sql
STABLE
SECURITY DEFINER
AS $$
SELECT 
    bs.id,
    bs.name,
    bs.latitude,
    bs.longitude,
    rs.stop_order,
    rs.travel_time_minutes
FROM public.route_stops rs
JOIN public.bus_stops bs ON rs.stop_id = bs.id
WHERE rs.route_id = p_route_id
ORDER BY rs.stop_order;
$$;

-- 6. Enable RLS
ALTER TABLE public.routes ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.bus_stops ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.route_stops ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.bus_schedules ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.bus_tracking ENABLE ROW LEVEL SECURITY;

-- 7. RLS Policies (Pattern 4: Public Read for Transportation Data)
-- All transportation data is publicly readable
CREATE POLICY "public_can_read_routes" ON public.routes
    FOR SELECT TO public USING (true);

CREATE POLICY "public_can_read_bus_stops" ON public.bus_stops
    FOR SELECT TO public USING (true);

CREATE POLICY "public_can_read_route_stops" ON public.route_stops
    FOR SELECT TO public USING (true);

CREATE POLICY "public_can_read_bus_schedules" ON public.bus_schedules
    FOR SELECT TO public USING (true);

CREATE POLICY "public_can_read_bus_tracking" ON public.bus_tracking
    FOR SELECT TO public USING (true);

-- Admin policies for data management (for future admin features)
CREATE POLICY "admin_manage_routes" ON public.routes
    FOR ALL TO authenticated USING (false) WITH CHECK (false); -- Disabled for now

CREATE POLICY "admin_manage_bus_stops" ON public.bus_stops
    FOR ALL TO authenticated USING (false) WITH CHECK (false); -- Disabled for now

-- 8. Triggers for updated_at timestamps
CREATE OR REPLACE FUNCTION public.update_updated_at_column()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$;

CREATE TRIGGER update_routes_updated_at
    BEFORE UPDATE ON public.routes
    FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();

CREATE TRIGGER update_bus_stops_updated_at
    BEFORE UPDATE ON public.bus_stops
    FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();

-- 9. Mock Data for SIBU Transportation System
DO $$
DECLARE
    -- Route IDs
    boquete_david_id UUID := gen_random_uuid();
    david_boquete_id UUID := gen_random_uuid();
    palmira_david_id UUID := gen_random_uuid();
    david_palmira_id UUID := gen_random_uuid();
    caldera_david_id UUID := gen_random_uuid();
    david_caldera_id UUID := gen_random_uuid();
    
    -- Stop IDs for Boquete area
    terminal_boquete_id UUID := gen_random_uuid();
    centro_boquete_id UUID := gen_random_uuid();
    parque_boquete_id UUID := gen_random_uuid();
    hospital_boquete_id UUID := gen_random_uuid();
    escuela_boquete_id UUID := gen_random_uuid();
    mercado_boquete_id UUID := gen_random_uuid();
    
    -- Stop IDs for David area
    terminal_david_id UUID := gen_random_uuid();
    centro_david_id UUID := gen_random_uuid();
    hospital_david_id UUID := gen_random_uuid();
    mall_david_id UUID := gen_random_uuid();
    
    -- Stop IDs for Palmira
    centro_palmira_id UUID := gen_random_uuid();
    escuela_palmira_id UUID := gen_random_uuid();
    
    -- Stop IDs for Caldera
    puerto_caldera_id UUID := gen_random_uuid();
    centro_caldera_id UUID := gen_random_uuid();
BEGIN
    -- Insert Routes
    INSERT INTO public.routes (id, name, description, origin_city, destination_city, distance_km, estimated_duration_minutes, status) VALUES
        (boquete_david_id, 'Boquete>David', 'Ruta desde Boquete hacia David con paradas principales', 'Boquete', 'David', 38.5, 45, 'active'),
        (david_boquete_id, 'David>Boquete', 'Ruta desde David hacia Boquete con paradas principales', 'David', 'Boquete', 38.5, 45, 'active'),
        (palmira_david_id, 'Palmira>David', 'Ruta desde Palmira hacia David', 'Palmira', 'David', 25.2, 35, 'active'),
        (david_palmira_id, 'David>Palmira', 'Ruta desde David hacia Palmira', 'David', 'Palmira', 25.2, 35, 'active'),
        (caldera_david_id, 'Caldera>David', 'Ruta desde Caldera hacia David', 'Caldera', 'David', 42.8, 50, 'active'),
        (david_caldera_id, 'David>Caldera', 'Ruta desde David hacia Caldera', 'David', 'Caldera', 42.8, 50, 'active');

    -- Insert Bus Stops
    INSERT INTO public.bus_stops (id, name, latitude, longitude, city, address, stop_type, has_shelter, has_seating) VALUES
        -- Boquete stops
        (terminal_boquete_id, 'Terminal de Boquete', 8.7697, -82.4328, 'Boquete', 'Centro de Boquete', 'terminal', true, true),
        (centro_boquete_id, 'Centro de Boquete', 8.7720, -82.4315, 'Boquete', 'Calle Central', 'regular', true, true),
        (parque_boquete_id, 'Parque Central Boquete', 8.7705, -82.4340, 'Boquete', 'Junto al Parque Central', 'regular', false, true),
        (hospital_boquete_id, 'Hospital de Boquete', 8.7680, -82.4350, 'Boquete', 'Hospital Regional', 'regular', true, true),
        (escuela_boquete_id, 'Escuela Primaria Boquete', 8.7740, -82.4300, 'Boquete', 'Zona Educativa', 'regular', false, false),
        (mercado_boquete_id, 'Mercado Municipal Boquete', 8.7715, -82.4365, 'Boquete', 'Mercado Central', 'regular', true, true),
        
        -- David stops  
        (terminal_david_id, 'Terminal de David', 8.4177, -82.4270, 'David', 'Terminal de Transporte', 'terminal', true, true),
        (centro_david_id, 'Centro de David', 8.4194, -82.4255, 'David', 'Parque Cervantes', 'regular', true, true),
        (hospital_david_id, 'Hospital Chiriquí', 8.4156, -82.4289, 'David', 'Complejo Hospitalario', 'regular', true, true),
        (mall_david_id, 'Chiriquí Mall', 8.4089, -82.4178, 'David', 'Centro Comercial', 'regular', true, true),
        
        -- Palmira stops
        (centro_palmira_id, 'Centro de Palmira', 8.3544, -82.3611, 'Palmira', 'Plaza Central', 'regular', true, true),
        (escuela_palmira_id, 'Escuela de Palmira', 8.3567, -82.3598, 'Palmira', 'Zona Escolar', 'regular', false, true),
        
        -- Caldera stops
        (puerto_caldera_id, 'Puerto de Caldera', 8.2456, -81.7234, 'Caldera', 'Zona Portuaria', 'terminal', true, true),
        (centro_caldera_id, 'Centro de Caldera', 8.2478, -81.7198, 'Caldera', 'Centro del Pueblo', 'regular', true, false);

    -- Insert Route Stops (Boquete > David)
    INSERT INTO public.route_stops (route_id, stop_id, stop_order, travel_time_minutes, is_pickup_point, is_dropoff_point) VALUES
        (boquete_david_id, terminal_boquete_id, 1, 0, true, false),
        (boquete_david_id, centro_boquete_id, 2, 3, true, true),
        (boquete_david_id, parque_boquete_id, 3, 2, true, true),
        (boquete_david_id, hospital_boquete_id, 4, 3, true, true),
        (boquete_david_id, mall_david_id, 5, 35, true, true),
        (boquete_david_id, centro_david_id, 6, 5, true, true),
        (boquete_david_id, terminal_david_id, 7, 3, false, true);

    -- Insert Route Stops (David > Boquete)
    INSERT INTO public.route_stops (route_id, stop_id, stop_order, travel_time_minutes, is_pickup_point, is_dropoff_point) VALUES
        (david_boquete_id, terminal_david_id, 1, 0, true, false),
        (david_boquete_id, centro_david_id, 2, 3, true, true),
        (david_boquete_id, mall_david_id, 3, 5, true, true),
        (david_boquete_id, hospital_boquete_id, 4, 35, true, true),
        (david_boquete_id, parque_boquete_id, 5, 3, true, true),
        (david_boquete_id, centro_boquete_id, 6, 2, true, true),
        (david_boquete_id, terminal_boquete_id, 7, 3, false, true);

    -- Insert Route Stops (Palmira > David)
    INSERT INTO public.route_stops (route_id, stop_id, stop_order, travel_time_minutes, is_pickup_point, is_dropoff_point) VALUES
        (palmira_david_id, centro_palmira_id, 1, 0, true, false),
        (palmira_david_id, escuela_palmira_id, 2, 2, true, true),
        (palmira_david_id, hospital_david_id, 3, 25, true, true),
        (palmira_david_id, centro_david_id, 4, 5, true, true),
        (palmira_david_id, terminal_david_id, 5, 3, false, true);

    -- Insert Route Stops (David > Palmira)
    INSERT INTO public.route_stops (route_id, stop_id, stop_order, travel_time_minutes, is_pickup_point, is_dropoff_point) VALUES
        (david_palmira_id, terminal_david_id, 1, 0, true, false),
        (david_palmira_id, centro_david_id, 2, 3, true, true),
        (david_palmira_id, hospital_david_id, 3, 5, true, true),
        (david_palmira_id, escuela_palmira_id, 4, 25, true, true),
        (david_palmira_id, centro_palmira_id, 5, 2, false, true);

    -- Insert Route Stops (Caldera > David)
    INSERT INTO public.route_stops (route_id, stop_id, stop_order, travel_time_minutes, is_pickup_point, is_dropoff_point) VALUES
        (caldera_david_id, puerto_caldera_id, 1, 0, true, false),
        (caldera_david_id, centro_caldera_id, 2, 3, true, true),
        (caldera_david_id, hospital_david_id, 3, 40, true, true),
        (caldera_david_id, centro_david_id, 4, 5, true, true),
        (caldera_david_id, terminal_david_id, 5, 3, false, true);

    -- Insert Route Stops (David > Caldera)  
    INSERT INTO public.route_stops (route_id, stop_id, stop_order, travel_time_minutes, is_pickup_point, is_dropoff_point) VALUES
        (david_caldera_id, terminal_david_id, 1, 0, true, false),
        (david_caldera_id, centro_david_id, 2, 3, true, true),
        (david_caldera_id, hospital_david_id, 3, 5, true, true),
        (david_caldera_id, centro_caldera_id, 4, 40, true, true),
        (david_caldera_id, puerto_caldera_id, 5, 3, false, true);

    -- Insert Bus Schedules
    INSERT INTO public.bus_schedules (route_id, departure_time, frequency_minutes, schedule_type, is_active) VALUES
        -- Boquete > David (every 30 minutes from 5:00 to 20:00)
        (boquete_david_id, '05:00:00', 30, 'weekday', true),
        (boquete_david_id, '05:30:00', 30, 'weekday', true),
        (boquete_david_id, '06:00:00', 30, 'weekday', true),
        (boquete_david_id, '06:30:00', 30, 'weekday', true),
        (boquete_david_id, '07:00:00', 30, 'weekday', true),
        (boquete_david_id, '07:30:00', 30, 'weekday', true),
        (boquete_david_id, '08:00:00', 30, 'weekday', true),
        (boquete_david_id, '08:30:00', 30, 'weekday', true),
        (boquete_david_id, '09:00:00', 30, 'weekday', true),
        (boquete_david_id, '09:30:00', 30, 'weekday', true),
        (boquete_david_id, '10:00:00', 30, 'weekday', true),
        (boquete_david_id, '10:30:00', 30, 'weekday', true),
        (boquete_david_id, '11:00:00', 30, 'weekday', true),
        (boquete_david_id, '11:30:00', 30, 'weekday', true),
        (boquete_david_id, '12:00:00', 30, 'weekday', true),
        (boquete_david_id, '12:30:00', 30, 'weekday', true),
        (boquete_david_id, '13:00:00', 30, 'weekday', true),
        (boquete_david_id, '13:30:00', 30, 'weekday', true),
        (boquete_david_id, '14:00:00', 30, 'weekday', true),
        (boquete_david_id, '14:30:00', 30, 'weekday', true),
        (boquete_david_id, '15:00:00', 30, 'weekday', true),
        (boquete_david_id, '15:30:00', 30, 'weekday', true),
        (boquete_david_id, '16:00:00', 30, 'weekday', true),
        (boquete_david_id, '16:30:00', 30, 'weekday', true),
        (boquete_david_id, '17:00:00', 30, 'weekday', true),
        (boquete_david_id, '17:30:00', 30, 'weekday', true),
        (boquete_david_id, '18:00:00', 30, 'weekday', true),
        (boquete_david_id, '18:30:00', 30, 'weekday', true),
        (boquete_david_id, '19:00:00', 30, 'weekday', true),
        (boquete_david_id, '19:30:00', 30, 'weekday', true),
        (boquete_david_id, '20:00:00', 30, 'weekday', true),
        
        -- David > Boquete (every 30 minutes from 5:30 to 20:30)
        (david_boquete_id, '05:30:00', 30, 'weekday', true),
        (david_boquete_id, '06:00:00', 30, 'weekday', true),
        (david_boquete_id, '06:30:00', 30, 'weekday', true),
        (david_boquete_id, '07:00:00', 30, 'weekday', true),
        (david_boquete_id, '07:30:00', 30, 'weekday', true),
        (david_boquete_id, '08:00:00', 30, 'weekday', true),
        (david_boquete_id, '08:30:00', 30, 'weekday', true),
        (david_boquete_id, '09:00:00', 30, 'weekday', true),
        (david_boquete_id, '09:30:00', 30, 'weekday', true),
        (david_boquete_id, '10:00:00', 30, 'weekday', true),
        (david_boquete_id, '10:30:00', 30, 'weekday', true),
        (david_boquete_id, '11:00:00', 30, 'weekday', true),
        (david_boquete_id, '11:30:00', 30, 'weekday', true),
        (david_boquete_id, '12:00:00', 30, 'weekday', true),
        (david_boquete_id, '12:30:00', 30, 'weekday', true),
        (david_boquete_id, '13:00:00', 30, 'weekday', true),
        (david_boquete_id, '13:30:00', 30, 'weekday', true),
        (david_boquete_id, '14:00:00', 30, 'weekday', true),
        (david_boquete_id, '14:30:00', 30, 'weekday', true),
        (david_boquete_id, '15:00:00', 30, 'weekday', true),
        (david_boquete_id, '15:30:00', 30, 'weekday', true),
        (david_boquete_id, '16:00:00', 30, 'weekday', true),
        (david_boquete_id, '16:30:00', 30, 'weekday', true),
        (david_boquete_id, '17:00:00', 30, 'weekday', true),
        (david_boquete_id, '17:30:00', 30, 'weekday', true),
        (david_boquete_id, '18:00:00', 30, 'weekday', true),
        (david_boquete_id, '18:30:00', 30, 'weekday', true),
        (david_boquete_id, '19:00:00', 30, 'weekday', true),
        (david_boquete_id, '19:30:00', 30, 'weekday', true),
        (david_boquete_id, '20:00:00', 30, 'weekday', true),
        (david_boquete_id, '20:30:00', 30, 'weekday', true),
        
        -- Palmira routes (every 60 minutes)
        (palmira_david_id, '06:00:00', 60, 'weekday', true),
        (palmira_david_id, '07:00:00', 60, 'weekday', true),
        (palmira_david_id, '08:00:00', 60, 'weekday', true),
        (palmira_david_id, '12:00:00', 60, 'weekday', true),
        (palmira_david_id, '17:00:00', 60, 'weekday', true),
        (palmira_david_id, '18:00:00', 60, 'weekday', true),
        
        (david_palmira_id, '08:00:00', 60, 'weekday', true),
        (david_palmira_id, '14:00:00', 60, 'weekday', true),
        (david_palmira_id, '18:00:00', 60, 'weekday', true),
        
        -- Caldera routes (every 45 minutes)
        (caldera_david_id, '05:30:00', 45, 'weekday', true),
        (caldera_david_id, '06:15:00', 45, 'weekday', true),
        (caldera_david_id, '07:00:00', 45, 'weekday', true),
        (caldera_david_id, '07:45:00', 45, 'weekday', true),
        (caldera_david_id, '16:00:00', 45, 'weekday', true),
        (caldera_david_id, '17:00:00', 45, 'weekday', true),
        
        (david_caldera_id, '09:00:00', 45, 'weekday', true),
        (david_caldera_id, '15:00:00', 45, 'weekday', true),
        (david_caldera_id, '18:30:00', 45, 'weekday', true);

    RAISE NOTICE 'SIBU Transportation System mock data created successfully!';
    
EXCEPTION
    WHEN OTHERS THEN
        RAISE NOTICE 'Error creating mock data: %', SQLERRM;
END $$;