-- 초기 데이터베이스 설정

-- Enum 타입 생성 (4개 카테고리)
CREATE TYPE userRole AS ENUM ('admin', 'user');
CREATE TYPE issueStatus AS ENUM ('new', 'progress', 'complete');
CREATE TYPE issueCategory AS ENUM (
    'material_missing',  -- 자재누락
    'design_error',      -- 설계미스
    'incoming_defect',   -- 입고자재 불량
    'inspection_miss'    -- 검사미스
);

-- 사용자 테이블
CREATE TABLE IF NOT EXISTS users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    hashed_password VARCHAR(255) NOT NULL,
    full_name VARCHAR(100),
    role userRole DEFAULT 'user',
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 이슈 테이블
CREATE TABLE IF NOT EXISTS issues (
    id SERIAL PRIMARY KEY,
    photo_path VARCHAR(500),
    photo_path2 VARCHAR(500),  -- 두 번째 사진
    category issueCategory NOT NULL,
    description TEXT NOT NULL,
    status issueStatus DEFAULT 'new',
    reporter_id INTEGER REFERENCES users(id),
    report_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    work_hours FLOAT DEFAULT 0,
    detail_notes TEXT
);

-- 일일 작업 테이블
CREATE TABLE IF NOT EXISTS daily_works (
    id SERIAL PRIMARY KEY,
    date DATE NOT NULL,
    worker_count INTEGER NOT NULL,
    regular_hours FLOAT NOT NULL,
    overtime_workers INTEGER DEFAULT 0,
    overtime_hours FLOAT DEFAULT 0,
    overtime_total FLOAT DEFAULT 0,
    total_hours FLOAT NOT NULL,
    created_by_id INTEGER REFERENCES users(id),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(date)
);

-- 인덱스 생성
CREATE INDEX idx_issues_reporter_id ON issues(reporter_id);
CREATE INDEX idx_issues_status ON issues(status);
CREATE INDEX idx_issues_category ON issues(category);
CREATE INDEX idx_daily_works_date ON daily_works(date);
CREATE INDEX idx_daily_works_created_by_id ON daily_works(created_by_id);