drop table if exists clients_initial_timestamps;


create temporary table clients_initial_timestamps as
select
	entity_id,
	created_at as init_time
FROM
	(SELECT 
		entity_id,
		created_at,
		row_number() over by_users as place
	from 
		db1.test.chat_messages cm 
	where created_by = 0
	window by_users as 
		(partition by entity_id, created_by order by created_at)) t1
where t1.place = 1;

select * from clients_initial_timestamps;

drop table if exists managers_response_timestamps;
create temporary table managers_response_timestamps as
select 
	entity_id,
	created_by as mop_id,
	created_at as responce_time
from 
	(SELECT 
		entity_id,
		created_by,
		created_at,
		row_number() over by_users as place
	from 
		db1.test.chat_messages cm 
	where created_by <> 0
	window by_users as 
		(partition by entity_id, created_by order by created_at)) t1
where 
	t1.place = 1;
	
select * from managers_response_timestamps;	
	
	
select 
	*,
	mrt.responce_time - cit.init_time as delta
from 
	clients_initial_timestamps as cit
	join 
	managers_response_timestamps as mrt
	on cit.entity_id = mrt.entity_id;

select 
	entity_id,
	count(*) as cnt
from 
	db1.test.chat_messages cm
group by entity_id 
order by cnt desc

select	
	created_by,
	created_at,
	rank() over(order by created_by) as dr
from 
	db1.test.chat_messages cm 	
where entity_id = 36541651
order by created_at 
	
	
select
	*,
	row_number() over(partition by entity_id order by created_at)
from 
	chat_messages cm 

	
	
	
	
	
select
	type,
	entity_id,
	created_by,
	created_at,
	created_at - lag(created_at) over(partition by entity_id, type order by created_at) as prev_msg_time,
	rank() over(partition by entity_id, type order by created_at) as nm
from 
	chat_messages cm
where 
	entity_id = 37548545
order by created_at 
offset 1;

with tmp as
(select 
	created_by,
	created_at,
	created_by = lag(created_by) over(order by created_at) as test
from
	chat_messages cm 
where 
	entity_id = 37548545
order by created_at)
select 
	*
from tmp
where tmp.test = false or tmp.test is null


select 
	entity_id,
	created_at,
	created_by,
	created_by = lag(created_by) over(partition by entity_id order by created_at) as tmp
from 
	chat_messages cm 
order by created_at 

-- result
with tmp as
(select 
	*,
	created_at - lag(created_at) over(order by created_at) as diff
from 
	chat_messages cm 
)
select 
--	*
	tmp.created_by,
	avg(diff)
from 
	tmp
where 
	tmp.diff is not null 
	and
	tmp.created_by <> 0
group by tmp.created_by	
	
	
	
select 
	created_by,
	extract(day from cast(to_timestamp(created_at) as date)) as time_casted,
	avg(cast(to_timestamp(created_at) as time)) over() as test
from 
	chat_messages cm 
	
	
select cast(to_timestamp(1729931470) as time)
	
select greatest(cast(to_timestamp(1729931470) as time),
		'12:00:00') as test	
	
	
	
	
	
	
	
with final_table2 as	
(with pre_table as
(select 
	*,
	-- Перевод из unix-времени в обычное
	cast(to_timestamp(created_at) as time) as dtime, 
	-- удаление подряд идущих сообщений от одного пользователя по принципу проверки равенства 
	-- между автором текущего и предыдущего сообщения (true, если авторы разные)
	-- coalesce -- чтобы NULL заменить на true у первого сообщения в сделке
	coalesce(created_by <> lag(created_by) over(partition by entity_id order by created_at), true) as not_dupl,
	-- нумерация записей внутри сделки, чтобы все сделки начинались с сообщения клиента
	row_number() over(partition by entity_id order by created_at) as num
from
	db1.test.chat_messages cm 
order by entity_id, created_at)
select 
	*,
	dtime,
	-- учет нерабочего времени, возможны 4 варианта
	-- 1) менеджер ответил ночью -- тогда время ответа равно 24:00 - `время сообщения клиента`
	-- 2) клиент написал ночью -- тогда время ответа отсчитывается от 09:30
	-- 3) клиент написал днем, а менеджер ответил на след. день -- тогда время ответа равно модулю
	--    разности времен сообщений (сделано через `greates`, так как interval не поддерживается `abs`)
	case when (dtime < '09:30:00'::time and created_by <> 0)
			then '24:00:00'::time - lag(dtime) over(partition by entity_id order by created_at)
		 when (dtime < '09:30:00'::time and created_by = 0)
		 	then dtime -'09:30:00'::time 
		 when (lag(dtime) over(partition by entity_id order by created_at) > dtime)
		 	then greatest(dtime - lag(dtime) over(partition by entity_id order by created_at),
		 	              lag(dtime) over(partition by entity_id order by created_at) - dtime)
		 else dtime - lag(dtime) over(partition by entity_id order by created_at)
	end as diff_time
from pre_table
where 
	  -- игнорируем дупликаты
	  pre_table.not_dupl
	  and
	  -- игнорируем записи в сделках, которые начинаются с сообщения менеджера
	  not (pre_table.num = 1 and pre_table.created_by <> 0))
select 
	r.rop_name,
	m.name_mop,
	-- приведение к timestamp для фильтрации в datalens
	cast(to_timestamp(created_at) as timestamp) as datetime,
	extract(epoch from diff_time) as diff_time
from 
	-- обычный INNER JOIN трех таблиц
	final_table2 as ft2
	join
	managers as m on m.mop_id = ft2.created_by
	join 
	-- пришлось привести m.rop_id к int4, так как разные типы
	rops as r on r.rop_id = cast(m.rop_id as int4)
where
	created_by <> 0 
		
select abs('09:35:00'::time - '09:36:00'::time)
		
		
		
		
		
		
		
	