-- 消课 / 课时包 / 流水（MVP 表结构；排课外键列统一为 kecheng_id）

CREATE TABLE course_hour_package (
    id VARCHAR NOT NULL PRIMARY KEY,
    student_id VARCHAR NOT NULL,
    ws_course_id VARCHAR,
    total_hours DOUBLE PRECISION NOT NULL DEFAULT 0,
    used_hours DOUBLE PRECISION NOT NULL DEFAULT 0,
    remaining_hours DOUBLE PRECISION NOT NULL DEFAULT 0,
    expire_date TIMESTAMP,
    package_status VARCHAR NOT NULL DEFAULT 'ACTIVE',
    created_at TIMESTAMP NOT NULL,
    created_by VARCHAR,
    updated_at TIMESTAMP,
    is_delete BOOLEAN DEFAULT FALSE
);

COMMENT ON TABLE course_hour_package IS '学员课时包（教学域 course.id 可选记在 ws_course_id）';
COMMENT ON COLUMN course_hour_package.ws_course_id IS '可选：关联 htyws.course.id，跨库不加 FK';

CREATE INDEX idx_course_hour_package_student ON course_hour_package (student_id);

CREATE TABLE hour_transaction (
    id VARCHAR NOT NULL PRIMARY KEY,
    student_id VARCHAR NOT NULL,
    package_id VARCHAR NOT NULL REFERENCES course_hour_package (id),
    amount DOUBLE PRECISION NOT NULL,
    transaction_type VARCHAR NOT NULL,
    kecheng_id VARCHAR REFERENCES kecheng (id),
    operator_hty_id VARCHAR,
    remark VARCHAR,
    created_at TIMESTAMP NOT NULL
);

COMMENT ON TABLE hour_transaction IS '课时变动流水；消课关联 kecheng_id';
CREATE INDEX idx_hour_transaction_student ON hour_transaction (student_id);
CREATE INDEX idx_hour_transaction_package ON hour_transaction (package_id);
CREATE INDEX idx_hour_transaction_kecheng ON hour_transaction (kecheng_id);

CREATE TABLE kecheng_attendance (
    id VARCHAR NOT NULL PRIMARY KEY,
    kecheng_id VARCHAR NOT NULL REFERENCES kecheng (id),
    student_id VARCHAR NOT NULL,
    course_hour_package_id VARCHAR REFERENCES course_hour_package (id),
    status VARCHAR NOT NULL,
    deducted_hours DOUBLE PRECISION NOT NULL DEFAULT 0,
    sign_time TIMESTAMP NOT NULL,
    sign_method VARCHAR,
    created_at TIMESTAMP NOT NULL,
    created_by VARCHAR,
    is_delete BOOLEAN DEFAULT FALSE
);

COMMENT ON TABLE kecheng_attendance IS '排课消课记录；status 如 NORMAL/LEAVE/ABSENT/MANUAL';
CREATE INDEX idx_kecheng_attendance_kecheng ON kecheng_attendance (kecheng_id);
CREATE INDEX idx_kecheng_attendance_student ON kecheng_attendance (student_id);
