CREATE TABLE feedback_sessions (
  id UUID PRIMARY KEY,
  owner_id UUID NOT NULL,
  profile_id UUID REFERENCES student_profiles(id) ON DELETE CASCADE,
  feedback_date DATE NOT NULL,
  content TEXT NOT NULL DEFAULT '',
  status VARCHAR(16) NOT NULL DEFAULT 'active'
    CHECK (status IN ('active', 'finalized')),
  finalized_record_id UUID REFERENCES feedback_records(id) ON DELETE SET NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX feedback_sessions_owner_status_idx
  ON feedback_sessions (owner_id, status, updated_at DESC);

CREATE UNIQUE INDEX feedback_sessions_one_active_idx
  ON feedback_sessions (owner_id, COALESCE(profile_id, '00000000-0000-0000-0000-000000000000'::UUID))
  WHERE status = 'active';

CREATE TABLE lesson_sessions (
  id UUID PRIMARY KEY,
  feedback_session_id UUID NOT NULL REFERENCES feedback_sessions(id) ON DELETE CASCADE,
  sequence INTEGER NOT NULL CHECK (sequence > 0),
  status VARCHAR(16) NOT NULL DEFAULT 'recording'
    CHECK (status IN ('recording', 'processing', 'ready', 'failed')),
  duration_ms INTEGER NOT NULL DEFAULT 0 CHECK (duration_ms >= 0),
  applied_directly BOOLEAN NOT NULL DEFAULT FALSE,
  included_in_generation BOOLEAN NOT NULL DEFAULT FALSE,
  started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  ended_at TIMESTAMPTZ,
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  UNIQUE (feedback_session_id, sequence)
);

CREATE INDEX lesson_sessions_feedback_session_idx
  ON lesson_sessions (feedback_session_id, sequence);

CREATE TABLE audio_segments (
  id UUID PRIMARY KEY,
  lesson_session_id UUID NOT NULL REFERENCES lesson_sessions(id) ON DELETE CASCADE,
  sequence INTEGER NOT NULL CHECK (sequence > 0),
  duration_ms INTEGER NOT NULL CHECK (duration_ms > 0),
  audio_format VARCHAR(8) NOT NULL,
  audio_path TEXT NOT NULL,
  status VARCHAR(16) NOT NULL DEFAULT 'processing'
    CHECK (status IN ('processing', 'ready', 'failed')),
  transcript TEXT,
  error_message TEXT,
  provider_request_id VARCHAR(100),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  UNIQUE (lesson_session_id, sequence)
);

CREATE INDEX audio_segments_lesson_session_idx
  ON audio_segments (lesson_session_id, sequence);
