create or replace view centile_daemon.v_in_centile_user_account as select * from user_account_centile.user_account;


create or replace view centile_daemon.v_in_user_account_alive as
select
    cau_alive.`id`,
    cau_alive.`cookie`,
    cau_alive.`x_application`,
    cau_alive.`centile_user_account_id`
from centile_auth_user.`v_out_user_account_alive` cau_alive;


create or replace view centile_daemon.v_in_user_terminal_choose as
select
    ct_utc.`id`,
    ct_utc.`terminal_id`,
    ct_utc.`centile_user_account_id`
from centile_terminals.`v_user_terminal_choose` ct_utc;


create or replace view centile_daemon.v_btw_user_daemon_first_time as
SELECT cd_v_uaa.centile_user_account_id AS centile_user_account_id
FROM centile_daemon.v_in_user_account_alive cd_v_uaa
WHERE cd_v_uaa.centile_user_account_id NOT IN (
    SELECT cd_ct.centile_user_account_id
    FROM centile_daemon.cron_task cd_ct
);


create or replace view centile_daemon.v_btw_daemon_need_to_plan_refresh as
SELECT
    cd_ud.id AS user_deamon_alive_id,
    cd_ct.centile_user_account_id AS centile_user_account_id,
    (cd_ud.expirated_at + INTERVAL - 30 MINUTE) AS plan_next_at
FROM
    centile_daemon.user_daemon cd_ud

INNER JOIN centile_daemon.cron_task cd_ct 
    ON cd_ud.cron_task_id = cd_ct.id

INNER JOIN ( 
        SELECT MAX(cd_us_in.`expirated_at`) max_expirated_at, cd_us_in.`centile_user_account_id`
        FROM centile_daemon.user_daemon cd_us_in
        INNER JOIN centile_daemon.cron_task cd_ct_in
            ON cd_us_in.`cron_task_id` = cd_ct_in.id
        GROUP BY cd_us_in.centile_user_account_id
)  max_cd_ud
    ON cd_ud.expirated_at = max_cd_ud.max_expirated_at AND cd_ct.centile_user_account_id = max_cd_ud.centile_user_account_id

WHERE cd_ct.centile_user_account_id NOT IN (
    SELECT cd_ct.centile_user_account_id
    FROM centile_daemon.cron_task cd_ct
    WHERE cd_ct.executed_at IS NULL
)
AND  NOW() >= (cd_ud.expirated_at + INTERVAL -35 MINUTE)
AND NOW() <= cd_ud.expirated_at  ;





