create extension citext; -- noqa
create extension unaccent;

create or replace function immutable_unaccent(text)
returns text as $$
  select unaccent('unaccent', $1);
$$ language sql immutable;

create table public.ingest_batch
(
    id serial primary key,

    elapsed_ms int not null default 0,
    file_checksum text not null unique,

    created_at timestamp not null default now()
);

create index idx_ingest_batch_file_checksum on public.ingest_batch (
    file_checksum
);

create table public.meteo_data
(
    id serial primary key,
    batch_id int not null references public.ingest_batch (id),

    location_name citext not null,
    location_name_norm text generated always as (immutable_unaccent(lower(location_name))) stored,
    date_of_register date not null,
    max_temp numeric(5, 2) not null,
    min_temp numeric(5, 2) not null,
    rainfall numeric(5, 2) not null,
    cloudiness int not null,

    created_at timestamp not null default now(),

    constraint uq_meteo_data_record unique (location_name_norm, date_of_register, max_temp, min_temp, rainfall, cloudiness)
);

create index idx_meteo_data_location_name_norm on public.meteo_data (location_name_norm);

create table public.rejected_data
(
    id serial primary key,
    batch_id int not null references public.ingest_batch (id),

    raw_data text not null,
    reason text default null,

    created_at timestamp not null default now()
)
