CREATE DATABASE IF NOT EXISTS aihub CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE aihub;

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(150),
  email VARCHAR(190) NOT NULL UNIQUE,
  password_hash VARCHAR(255),
  is_verified TINYINT(1) DEFAULT 0,
  verify_token VARCHAR(255) NULL,
  google_id VARCHAR(255) NULL,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;

CREATE TABLE wallets (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  balance DECIMAL(18,6) NOT NULL DEFAULT 0,
  currency VARCHAR(10) DEFAULT 'TRY',
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE wallet_transactions (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  wallet_id INT NOT NULL,
  type ENUM('credit','debit') NOT NULL,
  amount DECIMAL(18,6) NOT NULL,
  ref VARCHAR(128),
  meta JSON,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (wallet_id) REFERENCES wallets(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE transactions (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  gateway VARCHAR(32) NOT NULL,
  gateway_order_id VARCHAR(128),
  amount DECIMAL(18,2) NOT NULL,
  currency VARCHAR(10) DEFAULT 'TRY',
  status ENUM('pending','success','failed') DEFAULT 'pending',
  meta JSON,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE chats (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  model_code VARCHAR(64) NOT NULL,
  user_message LONGTEXT NOT NULL,
  assistant_response LONGTEXT,
  prompt_tokens INT DEFAULT 0,
  completion_tokens INT DEFAULT 0,
  cost DECIMAL(18,6) DEFAULT 0.0,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE invites (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  code VARCHAR(64) NOT NULL UNIQUE,
  uses INT DEFAULT 0,
  max_uses INT DEFAULT 10,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE invite_claims (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  invite_id INT NOT NULL,
  claimed_by INT NOT NULL,
  credit_amount DECIMAL(18,6) DEFAULT 0,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (invite_id) REFERENCES invites(id) ON DELETE CASCADE,
  FOREIGN KEY (claimed_by) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB;
