CREATE TABLE classroom_compliance_class (
	id BIGSERIAL PRIMARY KEY,
	number INT NOT NULL
		CONSTRAINT class_number_check CHECK (number > 0),
	school_year VARCHAR(9) NOT NULL,
	user_id BIGINT NOT NULL
		REFERENCES auth_user(id)
			ON UPDATE CASCADE ON DELETE CASCADE,
	score_expression VARCHAR(255) NOT NULL DEFAULT '0.5 * phone + 0.5 * behavior',
	score_period VARCHAR(64) NOT NULL DEFAULT 'week',
	CONSTRAINT unique_class_numbers_per_school_year
		UNIQUE(number, school_year, user_id)
);

CREATE TABLE classroom_compliance_student (
	id BIGSERIAL PRIMARY KEY,
	name VARCHAR(255) NOT NULL,
	class_id BIGINT NOT NULL
		REFERENCES classroom_compliance_class(id)
			ON UPDATE CASCADE ON DELETE CASCADE,
	desk_number INT NOT NULL DEFAULT 0,
	removed BOOLEAN NOT NULL DEFAULT FALSE
);

CREATE TABLE classroom_compliance_entry (
	id BIGSERIAL PRIMARY KEY,
	class_id BIGINT NOT NULL
		REFERENCES classroom_compliance_class(id)
			ON UPDATE CASCADE ON DELETE CASCADE,
	student_id BIGINT NOT NULL
		REFERENCES classroom_compliance_student(id)
			ON UPDATE CASCADE ON DELETE CASCADE,
	date DATE NOT NULL,
	created_at BIGINT NOT NULL
		DEFAULT EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000,
	absent BOOLEAN NOT NULL DEFAULT FALSE,
	comment VARCHAR(2000) NOT NULL DEFAULT '',
	phone_compliant BOOLEAN NULL DEFAULT NULL,
	behavior_rating INT NULL DEFAULT NULL,
	CONSTRAINT absence_nulls_check CHECK (
		(absent AND phone_compliant IS NULL AND behavior_rating IS NULL) OR
		(NOT absent AND phone_compliant IS NOT NULL AND behavior_rating IS NOT NULL)
	),
	CONSTRAINT unique_entry_per_date
		UNIQUE(class_id, student_id, date)
);

CREATE TABLE classroom_compliance_class_note (
	id BIGSERIAL PRIMARY KEY,
	class_id BIGINT NOT NULL
		REFERENCES classroom_compliance_class(id)
			ON UPDATE CASCADE ON DELETE CASCADE,
	created_at BIGINT NOT NULL
		DEFAULT EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000,
	content VARCHAR(2000) NOT NULL
);
