-- migrations/006_users.sql

CREATE TABLE IF NOT EXISTS users (
  id            UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  username      VARCHAR(100) UNIQUE NOT NULL,
  password_hash VARCHAR(255) NOT NULL,
  full_name     VARCHAR(255),
  email         VARCHAR(255),
  role          VARCHAR(20) DEFAULT 'pharmacist',  -- 'admin' veya 'pharmacist'
  is_active     BOOLEAN DEFAULT true,
  is_approved   BOOLEAN DEFAULT false,             -- admin onayı gerekiyor
  created_at    TIMESTAMP DEFAULT NOW(),
  updated_at    TIMESTAMP DEFAULT NOW()
);

-- Ekran-kullanıcı ilişki tablosu (bir ekran birden fazla kullanıcıya atanabilir)
CREATE TABLE IF NOT EXISTS user_screens (
  user_id   UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  screen_id UUID NOT NULL REFERENCES screens(id) ON DELETE CASCADE,
  PRIMARY KEY (user_id, screen_id)
);

CREATE INDEX IF NOT EXISTS idx_user_screens_user ON user_screens(user_id);
CREATE INDEX IF NOT EXISTS idx_user_screens_screen ON user_screens(screen_id);

-- updated_at trigger
CREATE OR REPLACE FUNCTION update_users_updated_at()
RETURNS TRIGGER AS $$
BEGIN NEW.updated_at = NOW(); RETURN NEW; END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER users_updated_at
  BEFORE UPDATE ON users
  FOR EACH ROW EXECUTE FUNCTION update_users_updated_at();
