-- ============================================================
-- TopTran — PostgreSQL table creation script
-- ============================================================
-- NOTE: The "users" table already exists with the schema below.
-- Do NOT run the commented block if it already exists.
-- ============================================================

-- [EXISTING TABLE — DO NOT RECREATE]
-- CREATE TABLE IF NOT EXISTS users (
--   id         TEXT        PRIMARY KEY,
--   name       TEXT        NOT NULL,
--   email      TEXT        NOT NULL UNIQUE,
--   password   TEXT        NOT NULL,
--   "createdAt" TIMESTAMPTZ DEFAULT NOW(),
--   "updatedAt" TIMESTAMPTZ DEFAULT NOW()
-- );

-- ============================================================
-- Companies
-- ============================================================
CREATE TABLE IF NOT EXISTS companies (
  id           TEXT          PRIMARY KEY,
  name         TEXT          NOT NULL,
  cost_per_km  NUMERIC(10,2) NOT NULL,
  notes        TEXT          DEFAULT '',
  "createdAt"  TIMESTAMPTZ   DEFAULT NOW(),
  "updatedAt"  TIMESTAMPTZ   DEFAULT NOW()
);

-- ============================================================
-- Rides
-- ============================================================
CREATE TABLE IF NOT EXISTS rides (
  id           TEXT          PRIMARY KEY,
  user_id      TEXT          NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  company      TEXT          NOT NULL,
  km           NUMERIC(10,2) NOT NULL,
  cost_per_km  NUMERIC(10,2) NOT NULL,
  total        NUMERIC(10,2) NOT NULL,
  ride_date    TEXT          NOT NULL,
  synced       SMALLINT      DEFAULT 0,
  "createdAt"  TIMESTAMPTZ   DEFAULT NOW(),
  "updatedAt"  TIMESTAMPTZ   DEFAULT NOW()
);

-- ============================================================
-- Indexes
-- ============================================================
CREATE INDEX IF NOT EXISTS idx_rides_user_id   ON rides(user_id);
CREATE INDEX IF NOT EXISTS idx_rides_synced    ON rides(synced);
CREATE INDEX IF NOT EXISTS idx_companies_name  ON companies(name);
