-- Payments

CREATE TABLE IF NOT EXISTS "payments"(
  "id" INTEGER PRIMARY KEY,
  "user_id" INTEGER NOT NULL REFERENCES "users",
  "name" TEXT NOT NULL,
  "cost" INTEGER NOT NULL,
  "date" DATE NOT NULL,
  "frequency" TEXT NOT NULL,
  "category_id" INTEGER NOT NULL REFERENCES "categories",
  "created_at" DATE NULL DEFAULT (datetime('now')),
  "updated_at" DATE NULL,
  "deleted_at" DATE NULL
);

INSERT INTO payments (id, user_id, name, cost, date, frequency, category_id, created_at, updated_at, deleted_at)
  SELECT id, user_id, name, cost, date, frequency, category, created_at, edited_at, deleted_at
  FROM payment;

DROP TABLE payment;

CREATE INDEX payment_date ON payments(date);

-- Categories

CREATE TABLE IF NOT EXISTS "categories"(
  "id" INTEGER PRIMARY KEY,
  "name" TEXT NOT NULL,
  "color" TEXT NOT NULL,
  "created_at" DATE NULL DEFAULT (datetime('now')),
  "updated_at" DATE NULL,
  "deleted_at" DATE NULL
);

INSERT INTO categories (id, name, color, created_at, updated_at, deleted_at)
  SELECT id, name, color, created_at, edited_at, deleted_at
  FROM category;

DROP TABLE category;

-- Users

CREATE TABLE IF NOT EXISTS "users"(
  "id" INTEGER PRIMARY KEY,
  "email" TEXT NOT NULL,
  "name" TEXT NOT NULL,
  "password" TEXT NOT NULL,
  "login_token" TEXT NULL,
  "created_at" DATE NULL DEFAULT (datetime('now')),
  "updated_at" DATE NULL,
  "deleted_at" DATE NULL,
  CONSTRAINT "uniq_user_email" UNIQUE ("email"),
  CONSTRAINT "uniq_user_name" UNIQUE ("name")
);

INSERT INTO users (id, created_at, email, name, password, login_token)
  SELECT id, creation, email, name, password, sign_in_token
  FROM user;

DROP TABLE user;

-- Jobs

CREATE TABLE IF NOT EXISTS "jobs"(
  "name" TEXT PRIMARY KEY,
  "last_execution" DATE NOT NULL DEFAULT (datetime('now'))
);

INSERT INTO jobs (name, last_execution)
  SELECT kind, last_execution
  FROM job;

DROP TABLE job;

-- Incomes

CREATE TABLE IF NOT EXISTS "incomes"(
  "id" INTEGER PRIMARY KEY,
  "user_id" INTEGER NOT NULL REFERENCES "users",
  "date" DATE NOT NULL,
  "amount" INTEGER NOT NULL,
  "created_at" DATE NULL DEFAULT (datetime('now')),
  "updated_at" DATE NULL,
  "deleted_at" DATE NULL
);

INSERT INTO incomes (id, user_id, date, amount, created_at, updated_at, deleted_at)
  SELECT id, user_id, date, amount, created_at, edited_at, deleted_at
  FROM income;

DROP TABLE income;
