CREATE TABLE IF NOT EXISTS acl.schedule (
    id bigserial PRIMARY KEY,
    date_start date NOT NULL,
    date_end date,
    weekdays smallint,
    work_rest_days_sequence_array jsonb,
    time_start time with time zone,
    time_end time with time zone,

    CONSTRAINT weekdays_or_days_sequence CHECK (weekdays IS NOT NULL OR work_rest_days_sequence_array IS NOT NULL)
);

CREATE TABLE IF NOT EXISTS acl.schedule_policy (
    agent_id bigint NOT NULL,
    role_id bigint NOT NULL,
    aoi_id bigint NOT NULL DEFAULT 0,
    schedule_id bigint NOT NULL,

    PRIMARY KEY (agent_id, role_id, aoi_id, schedule_id),

    CONSTRAINT schedule_policy_agent_id_fkey FOREIGN KEY (agent_id) REFERENCES acl.agent (id)
      ON DELETE CASCADE,
    CONSTRAINT schedule_policy_role_id_fkey FOREIGN KEY (role_id) REFERENCES acl.role (id)
      ON DELETE CASCADE,
    CONSTRAINT schedule_policy_schedule_id_fkey FOREIGN KEY (schedule_id) REFERENCES acl.schedule (id)
      ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS acl.schedule_group (
    user_id bigint NOT NULL,
    group_id bigint NOT NULL,
    schedule_id bigint NOT NULL,

    PRIMARY KEY (user_id, group_id, schedule_id),

    CONSTRAINT schedule_group_user_id_fkey FOREIGN KEY (user_id) REFERENCES acl."user" (id)
      ON DELETE CASCADE,
    CONSTRAINT schedule_group_group_id_fkey FOREIGN KEY (group_id) REFERENCES acl."group" (id)
      ON DELETE CASCADE,
    CONSTRAINT schedule_group_schedule_id_fkey FOREIGN KEY (schedule_id) REFERENCES acl.schedule (id)
      ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS schedule_policy_agent_idx ON acl.schedule_policy USING btree (agent_id);
CREATE INDEX IF NOT EXISTS schedule_group_user_idx ON acl.schedule_group USING btree (user_id);
