create extension if not exists citext;
create extension if not exists pgcrypto;
create extension if not exists btree_gist;

create type user_role as enum ('admin', 'operator', 'viewer');
create type equipment_status as enum ('active', 'service', 'retired');

create table if not exists users (
  id uuid primary key default gen_random_uuid(),
  name text not null,
  email citext not null unique,
  password_hash text not null,
  role user_role not null default 'viewer',
  is_active boolean not null default true,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

create table if not exists equipment_categories (
  id uuid primary key default gen_random_uuid(),
  name text not null unique,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

create table if not exists equipment_items (
  id uuid primary key default gen_random_uuid(),
  category_id uuid not null references equipment_categories(id) on delete restrict,
  name text not null,
  serial_number text unique,
  asset_tag text unique,
  status equipment_status not null default 'active',
  notes text,
  is_visible_on_timeline boolean not null default true,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

create index if not exists equipment_items_category_idx on equipment_items (category_id);
create index if not exists equipment_items_status_idx on equipment_items (status);

create table if not exists rental_bookings (
  id uuid primary key default gen_random_uuid(),
  equipment_item_id uuid not null references equipment_items(id) on delete cascade,
  customer_name text not null,
  order_number text,
  project_name text,
  notes text,
  start_date date not null,
  end_date date not null,
  created_by uuid references users(id) on delete set null,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now(),
  constraint rental_bookings_dates_check check (start_date <= end_date)
);

create index if not exists rental_bookings_item_idx on rental_bookings (equipment_item_id);
create index if not exists rental_bookings_customer_idx on rental_bookings (lower(customer_name));
create index if not exists rental_bookings_range_idx on rental_bookings (start_date, end_date);

alter table rental_bookings
  add constraint rental_bookings_no_overlap
  exclude using gist (
    equipment_item_id with =,
    daterange(start_date, end_date, '[]') with &&
  );
