import { Op } from "sequelize";
import { initDb } from "@/lib/db";
import type { Respondent } from "@/lib/db/models/respondent";
import type { SurveyStatus } from "@/types";

/** Fetch a survey scoped to a workspace — prevents cross-tenant leaks. */
export async function getScopedSurvey(surveyId: string, workspaceId: string) {
  const { Survey, Question } = initDb();
  return Survey.findOne({
    where: { id: surveyId, workspaceId },
    include: [
      {
        model: Question,
        as: "questions",
        separate: true,
        order: [["position", "ASC"]],
      },
    ],
  });
}

export interface SurveyListFilters {
  status?: SurveyStatus | "all";
  search?: string;
}

/** List surveys for a workspace with response counts. */
export async function getWorkspaceSurveys(
  workspaceId: string,
  filters: SurveyListFilters = {}
) {
  const { Survey, Respondent } = initDb();

  const where: Record<string, unknown> = { workspaceId };

  if (filters.status && filters.status !== "all") {
    where.status = filters.status;
  }

  if (filters.search?.trim()) {
    where.title = { [Op.like]: `%${filters.search.trim()}%` };
  }

  const surveys = await Survey.findAll({
    where,
    order: [["createdAt", "DESC"]],
    include: [
      {
        model: Respondent,
        as: "respondents",
        attributes: ["id", "status"],
        required: false,
      },
    ],
  });

  return surveys.map((survey) => {
    const respondents = survey.get("respondents") as Respondent[] | undefined;
    const responseCount =
      respondents?.filter((r) => r.status === "completed").length ?? 0;

    return {
      id: survey.id,
      title: survey.title,
      status: survey.status,
      responseCount,
      createdAt: survey.createdAt,
      publishedAt: survey.publishedAt,
    };
  });
}

export async function getSurveyResponseCount(surveyId: string): Promise<number> {
  const { Respondent } = initDb();
  return Respondent.count({
    where: { surveyId, status: "completed" },
  });
}
