CREATE TABLE IF NOT EXISTS users (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  subject VARCHAR(255) UNIQUE NOT NULL,
  email VARCHAR(255) NOT NULL DEFAULT '',
  name VARCHAR(255) NOT NULL DEFAULT '',
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS departments (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(120) UNIQUE NOT NULL
);
CREATE TABLE IF NOT EXISTS items (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  sku VARCHAR(120) UNIQUE NOT NULL,
  name VARCHAR(255) NOT NULL,
  category VARCHAR(120) NOT NULL DEFAULT 'item'
);
CREATE TABLE IF NOT EXISTS trade_requests (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  kind ENUM('buy','sell') NOT NULL,
  item_id BIGINT NOT NULL,
  quantity INT NOT NULL,
  price_limit DECIMAL(12,2) NOT NULL DEFAULT 0,
  source_department_id BIGINT NULL,
  target_department_id BIGINT NULL,
  status VARCHAR(60) NOT NULL DEFAULT 'new',
  created_by BIGINT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_trade_item FOREIGN KEY (item_id) REFERENCES items(id),
  CONSTRAINT fk_trade_source_dept FOREIGN KEY (source_department_id) REFERENCES departments(id),
  CONSTRAINT fk_trade_target_dept FOREIGN KEY (target_department_id) REFERENCES departments(id),
  CONSTRAINT fk_trade_user FOREIGN KEY (created_by) REFERENCES users(id),
  CONSTRAINT chk_trade_quantity CHECK (quantity > 0)
);
CREATE TABLE IF NOT EXISTS quests (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  parent_request_id BIGINT NULL,
  depends_on_quest_id BIGINT NULL,
  type VARCHAR(120) NOT NULL,
  title VARCHAR(255) NOT NULL,
  department_id BIGINT NULL,
  reward DECIMAL(12,2) NOT NULL DEFAULT 0,
  status VARCHAR(60) NOT NULL DEFAULT 'open',
  contractor_note TEXT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  CONSTRAINT fk_quest_request FOREIGN KEY (parent_request_id) REFERENCES trade_requests(id) ON DELETE CASCADE,
  CONSTRAINT fk_quest_depends FOREIGN KEY (depends_on_quest_id) REFERENCES quests(id),
  CONSTRAINT fk_quest_dept FOREIGN KEY (department_id) REFERENCES departments(id)
);
CREATE TABLE IF NOT EXISTS quest_updates (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  quest_id BIGINT NOT NULL,
  actor_user_id BIGINT NULL,
  status VARCHAR(60) NOT NULL,
  note TEXT NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_update_quest FOREIGN KEY (quest_id) REFERENCES quests(id) ON DELETE CASCADE,
  CONSTRAINT fk_update_actor FOREIGN KEY (actor_user_id) REFERENCES users(id)
);
CREATE TABLE IF NOT EXISTS events (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  type VARCHAR(120) NOT NULL,
  payload JSON NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS workflow_rules (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(255) NOT NULL UNIQUE,
  trigger_name VARCHAR(120) NOT NULL,
  condition_json JSON NOT NULL,
  actions_json JSON NOT NULL,
  enabled BOOLEAN NOT NULL DEFAULT true
);
INSERT IGNORE INTO departments(name) VALUES ('Trading'),('Mining'),('Logistik'),('Crafting'),('FPS');
INSERT IGNORE INTO items(sku,name,category) VALUES ('P4-AR','P4-AR','weapon'),('ORE','Erz','resource');
INSERT IGNORE INTO workflow_rules(name,trigger_name,condition_json,actions_json) VALUES
('Standard Beschaffung','request.created',JSON_OBJECT(),JSON_ARRAY('logistics_quote','mining_procure','crafting_order','delivery'));

CREATE TABLE IF NOT EXISTS app_settings (
  setting_key VARCHAR(120) PRIMARY KEY,
  setting_value TEXT NOT NULL,
  description VARCHAR(255) NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS status_options (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  scope ENUM('request','quest') NOT NULL,
  value VARCHAR(60) NOT NULL,
  label VARCHAR(120) NOT NULL,
  sort_order INT NOT NULL DEFAULT 100,
  is_terminal BOOLEAN NOT NULL DEFAULT false,
  UNIQUE KEY uq_status_scope_value (scope, value)
);
CREATE TABLE IF NOT EXISTS quest_templates (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  type VARCHAR(120) NOT NULL UNIQUE,
  title_template VARCHAR(255) NOT NULL,
  department_id BIGINT NULL,
  reward_percent DECIMAL(6,4) NOT NULL DEFAULT 0,
  enabled BOOLEAN NOT NULL DEFAULT true,
  sort_order INT NOT NULL DEFAULT 100,
  CONSTRAINT fk_template_dept FOREIGN KEY (department_id) REFERENCES departments(id)
);

INSERT IGNORE INTO app_settings(setting_key,setting_value,description) VALUES
('currency','aUEC','Währung für Preise und Belohnungen'),
('default_margin_percent','10','Standardmarge der Trading-Abteilung in Prozent'),
('auto_generate_quests','true','Automatisch Quests aus neuen Anfragen erzeugen'),
('admin_emails','','Kommagetrennte Admin-E-Mails. Leer bedeutet: jeder eingeloggte Nutzer darf Admin-Seiten öffnen.');

INSERT IGNORE INTO status_options(scope,value,label,sort_order,is_terminal) VALUES
('request','new','Neu',10,false),('request','quoted','Preisvorschlag',20,false),('request','approved','Freigegeben',30,false),('request','fulfilled','Erfüllt',90,true),('request','cancelled','Abgebrochen',99,true),
('quest','waiting','Wartet auf Abhängigkeit',5,false),('quest','open','Offen',10,false),('quest','accepted','Angenommen',20,false),('quest','in_progress','In Arbeit',30,false),('quest','blocked','Blockiert',40,false),('quest','change_requested','Änderung angefragt',50,false),('quest','done','Erledigt',90,true),('quest','cancelled','Abgebrochen',99,true);

INSERT IGNORE INTO quest_templates(type,title_template,department_id,reward_percent,sort_order)
SELECT 'logistics_quote','Materialbedarf und Transport prüfen',(SELECT id FROM departments WHERE name='Logistik'),0.0300,10;
INSERT IGNORE INTO quest_templates(type,title_template,department_id,reward_percent,sort_order)
SELECT 'mining_procure','Ressourcen für {{item}} beschaffen',(SELECT id FROM departments WHERE name='Mining'),0.2500,20;
INSERT IGNORE INTO quest_templates(type,title_template,department_id,reward_percent,sort_order)
SELECT 'crafting_order','{{item}} herstellen oder bereitstellen',(SELECT id FROM departments WHERE name='Crafting'),0.1500,30;
INSERT IGNORE INTO quest_templates(type,title_template,department_id,reward_percent,sort_order)
SELECT 'delivery','{{item}} an Zielabteilung liefern',(SELECT id FROM departments WHERE name='Logistik'),0.0500,40;
