import "server-only"

import { db } from "@/shared/db"
import { fileAttachments } from "@/shared/db/schema"
import { and, asc, eq } from "drizzle-orm"

import type { ScanAttachment } from "./types"

/**
 * 作业扫描图数据访问层 —— 仅供 homework/actions.ts 调用。
 *
 * 扫描图存储在 `fileAttachments` 表中，`targetType="homework"`、
 * `targetId=submissionId`。权限校验在 Server Action 层完成，
 * 本模块只负责 DB 查询与映射。
 */

/**
 * 查询某次提交的所有答题扫描图，按创建时间升序排列。
 *
 * @returns `ScanAttachment[]` —— `page` 字段为按顺序生成的页码（从 1 开始）。
 */
export async function getScansBySubmissionId(
  submissionId: string
): Promise<ScanAttachment[]> {
  const rows = await db
    .select({
      id: fileAttachments.id,
      url: fileAttachments.url,
      filename: fileAttachments.filename,
      originalName: fileAttachments.originalName,
      createdAt: fileAttachments.createdAt,
    })
    .from(fileAttachments)
    .where(
      and(
        eq(fileAttachments.targetType, "homework"),
        eq(fileAttachments.targetId, submissionId)
      )
    )
    .orderBy(asc(fileAttachments.createdAt))

  return rows.map((row, idx) => ({
    fileId: row.id,
    url: row.url ?? "",
    filename: row.filename,
    originalName: row.originalName,
    page: idx + 1,
  }))
}
