-- Schema PDIMaker
-- Criação de tabelas do sistema

-- Tipos ENUM
CREATE TYPE "Role" AS ENUM ('EMPLOYEE', 'MANAGER', 'HR_ADMIN');
CREATE TYPE "WorkspaceStatus" AS ENUM ('ACTIVE', 'ARCHIVED', 'PENDING_INVITE');
CREATE TYPE "InviteStatus" AS ENUM ('PENDING', 'ACCEPTED', 'EXPIRED', 'CANCELLED');
CREATE TYPE "JournalVisibility" AS ENUM ('PUBLIC', 'PRIVATE', 'SUMMARY');
CREATE TYPE "GoalType" AS ENUM ('TECHNICAL', 'SOFT_SKILL', 'LEADERSHIP', 'CAREER');
CREATE TYPE "GoalStatus" AS ENUM ('NOT_STARTED', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED');
CREATE TYPE "ActionStatus" AS ENUM ('PENDING', 'IN_PROGRESS', 'DONE', 'BLOCKED');
CREATE TYPE "AssessmentType" AS ENUM ('PERSONALITY', 'BEHAVIORAL', 'MOTIVATIONAL', 'VOCATIONAL', 'CUSTOM');
CREATE TYPE "OneOnOneStatus" AS ENUM ('SCHEDULED', 'COMPLETED', 'CANCELLED');

-- Tabela de Usuários
CREATE TABLE IF NOT EXISTS "users" (
  "id" TEXT PRIMARY KEY,
  "email" TEXT UNIQUE NOT NULL,
  "name" TEXT NOT NULL,
  "avatar" TEXT,
  "role" "Role" DEFAULT 'EMPLOYEE',
  "googleId" TEXT UNIQUE,
  "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  "updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  "lastLoginAt" TIMESTAMP
);

CREATE INDEX idx_users_email ON "users"("email");

-- Tabela de Workspaces
CREATE TABLE IF NOT EXISTS "workspaces" (
  "id" TEXT PRIMARY KEY,
  "slug" TEXT UNIQUE NOT NULL,
  "employeeId" TEXT NOT NULL REFERENCES "users"("id"),
  "managerId" TEXT NOT NULL REFERENCES "users"("id"),
  "hrId" TEXT REFERENCES "users"("id"),
  "status" "WorkspaceStatus" DEFAULT 'ACTIVE',
  "config" JSONB,
  "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  "updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE UNIQUE INDEX idx_workspace_employee_manager ON "workspaces"("employeeId", "managerId");
CREATE INDEX idx_workspaces_slug ON "workspaces"("slug");
CREATE INDEX idx_workspaces_employee ON "workspaces"("employeeId");
CREATE INDEX idx_workspaces_manager ON "workspaces"("managerId");

-- Tabela de Convites
CREATE TABLE IF NOT EXISTS "invites" (
  "id" TEXT PRIMARY KEY,
  "email" TEXT NOT NULL,
  "role" "Role" NOT NULL,
  "token" TEXT UNIQUE NOT NULL,
  "invitedBy" TEXT NOT NULL,
  "workspaceId" TEXT REFERENCES "workspaces"("id"),
  "status" "InviteStatus" DEFAULT 'PENDING',
  "expiresAt" TIMESTAMP NOT NULL,
  "acceptedAt" TIMESTAMP,
  "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_invites_email ON "invites"("email");
CREATE INDEX idx_invites_token ON "invites"("token");

-- Função para gerar IDs únicos (cuid)
CREATE EXTENSION IF NOT EXISTS "pgcrypto";

CREATE OR REPLACE FUNCTION generate_cuid() RETURNS TEXT AS $$
DECLARE
  timestamp_part TEXT;
  counter_part TEXT;
  random_part TEXT;
BEGIN
  timestamp_part := to_hex(extract(epoch from now())::bigint);
  counter_part := lpad(to_hex((random() * 65535)::int), 4, '0');
  random_part := encode(gen_random_bytes(12), 'hex');
  RETURN 'c' || timestamp_part || counter_part || random_part;
END;
$$ LANGUAGE plpgsql;

