-- Tables

CREATE TABLE IF NOT EXISTS usage_stats(
   rental_id BIGINT PRIMARY KEY,
   duration BIGINT,
   bike_id BIGINT,
   end_date TIMESTAMP,
   end_station_id BIGINT,
   end_station_name TEXT,
   start_date TIMESTAMP,
   start_station_id BIGINT,
   start_station_name TEXT
);

INSERT INTO usage_stats 
VALUES (40346508, 360, 12019, TO_TIMESTAMP(1420326360), 424, 'Ebury Bridge, Pimlico', TO_TIMESTAMP(1420326000), 368, 'Harriet Street, Knightsbridge')
ON CONFLICT DO NOTHING;

SELECT TO_TIMESTAMP(1420326360);


CREATE TABLE IF NOT EXISTS read_files(
	file_path TEXT, 
	etag TEXT PRIMARY KEY
);


CREATE TABLE IF NOT EXISTS bike_points(
   id TEXT PRIMARY KEY, 
   common_name TEXT,
   lat REAL,
   lon REAL,
   id_num BIGINT
);


CREATE TABLE IF NOT EXISTS accidents(
   id BIGINT PRIMARY KEY,
   lat REAL,
   lon REAL,
   location TEXT,
   date TEXT,
   severity TEXT
);

-- indicies

CREATE INDEX IF NOT EXISTS idx_station_start_and_end_date ON usage_stats (start_station_id, start_date, end_date);


SELECT COUNT(*) FROM usage_stats;

SELECT
    min(u.start_station_name) AS startStationName,
    u.end_station_name AS endStationName,
    count(*) AS number,
    round(avg(u.duration)) AS avgDuration
FROM usage_stats u
WHERE u.start_station_id = 512 AND u.start_date::DATE >= '2010-01-01'::DATE AND u.start_date::DATE <= '2022-01-15'::DATE
GROUP BY u.end_station_name
ORDER BY number DESC
LIMIT 3;



SELECT
     MIN(b.id_num) as id,
     MIN(b.common_name) AS commonName,
     MIN(b.lat),
     MIN(b.lon),
     max(u.start_date) AS maxEndDate, 
     min(u.start_date) AS maxStartDate
 FROM usage_stats u
 JOIN bike_points b ON u.start_station_id = b.id_num
 WHERE u.start_station_id = 306