-- Filamenteka PostgreSQL Schema

-- Enable UUID extension
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- Colors table
CREATE TABLE colors (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  name VARCHAR(100) NOT NULL UNIQUE,
  hex VARCHAR(7) NOT NULL,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Filaments table
CREATE TABLE filaments (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  brand VARCHAR(100) NOT NULL,
  tip VARCHAR(50) NOT NULL,
  finish VARCHAR(50) NOT NULL,
  boja VARCHAR(100) NOT NULL,
  boja_hex VARCHAR(7),
  refill VARCHAR(10),
  vakum VARCHAR(20),
  otvoreno VARCHAR(20),
  kolicina INTEGER DEFAULT 1,
  cena VARCHAR(50),
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_color FOREIGN KEY (boja) REFERENCES colors(name) ON UPDATE CASCADE
);

-- Create indexes for better performance
CREATE INDEX idx_filaments_brand ON filaments(brand);
CREATE INDEX idx_filaments_tip ON filaments(tip);
CREATE INDEX idx_filaments_boja ON filaments(boja);
CREATE INDEX idx_filaments_created_at ON filaments(created_at);

-- Create updated_at trigger function
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ language 'plpgsql';

-- Apply trigger to filaments table
CREATE TRIGGER update_filaments_updated_at BEFORE UPDATE
    ON filaments FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- Apply trigger to colors table
CREATE TRIGGER update_colors_updated_at BEFORE UPDATE
    ON colors FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- Insert default colors from legacy data
INSERT INTO colors (name, hex) VALUES
  ('Crna', '#000000'),
  ('Bela', '#FFFFFF'),
  ('Plava', '#0000FF'),
  ('Crvena', '#FF0000'),
  ('Zelena', '#00FF00'),
  ('Žuta', '#FFFF00'),
  ('Narandžasta', '#FFA500'),
  ('Ljubičasta', '#800080'),
  ('Siva', '#808080'),
  ('Braon', '#A52A2A')
ON CONFLICT (name) DO NOTHING;