create table if not exists quotes (
    id          serial       primary key,
    nick        citext       not null,
    item        text         not null,
    channel     varchar(32)  not null,
    created_by  varchar(30)  not null,
    created_at  timestamp    not null default current_timestamp,
    unique (nick, item)
);

create table if not exists mcmaniacs (
    id    serial  primary key,
    item  text    not null,
    unique (item)
);

create table if not exists timers (
    id          serial        primary key,
    mask        varchar(255)  not null,
    target      varchar(32)   not null,
    message     text          not null,
    delay       varchar(10)   not null,
    ends_at     timestamp     not null,
    created_at  timestamp     not null default current_timestamp
);

create table if not exists tells (
    id          serial       primary key,
    from_nick   varchar(30)  not null,
    to_nick     varchar(30)  not null,
    message     text         not null,
    created_at  timestamp    not null default current_timestamp,
    unique (to_nick, message)
);

create table if not exists seens (
    id       serial        primary key,
    nick     varchar(30)   not null,
    host     varchar(255)  not null,
    channel  varchar(32)   not null,
    message  text          not null,
    seen_at  timestamp     not null default current_timestamp,
    unique (nick)
);

create table if not exists users (
    id        serial        primary key,
    nick      varchar(30)   not null,
    husbando  varchar(255)  null,
    waifu     varchar(255)  null,
    fines     integer       default 0,
    unique (nick)
);

create table if not exists kills (
    id    serial  primary key,
    item  text    not null,
    unique (item)
);

create table if not exists yiffs (
    id    serial  primary key,
    item  text    not null,
    unique (item)
);

create table if not exists last_messages (
    id       serial        primary key,
    nick     varchar(30)   not null,
    host     varchar(255)  not null,
    channel  varchar(32)   not null,
    item     text          not null,
    unique (nick, channel)
);

create or replace function quotes_ci_nick_insert_fnc()
returns trigger as $$
begin
    NEW.nick = coalesce((select nick from quotes where nick = NEW.nick limit 1), NEW.nick);
    return NEW;
end $$ language 'plpgsql';

drop trigger if exists quotes_ci_nick_trigger on quotes;

create trigger quotes_ci_nick_trigger
before insert on quotes
for each row
execute procedure quotes_ci_nick_insert_fnc();
