import { eq, and, SQL, desc, gte, lte } from "drizzle-orm";
import { getDb } from "coze-coding-dev-sdk";
import { weightRecords, insertWeightRecordSchema } from "./shared/schema";
import type { WeightRecord, InsertWeightRecord } from "./shared/schema";

export class WeightRecordManager {
  async createWeightRecord(data: InsertWeightRecord): Promise<WeightRecord> {
    const db = await getDb();
    const validated = insertWeightRecordSchema.parse(data);
    const [record] = await db.insert(weightRecords).values(validated).returning();
    return record;
  }

  async getWeightRecords(options: {
    userId: string;
    skip?: number;
    limit?: number;
    startDate?: Date;
    endDate?: Date;
  }): Promise<WeightRecord[]> {
    const { userId, skip = 0, limit = 100, startDate, endDate } = options;
    const db = await getDb();

    const conditions: SQL[] = [];
    conditions.push(eq(weightRecords.userId, userId));

    if (startDate) {
      conditions.push(gte(weightRecords.recordedAt, startDate));
    }

    if (endDate) {
      conditions.push(lte(weightRecords.recordedAt, endDate));
    }

    let query = db.select().from(weightRecords).$dynamic();

    if (conditions.length > 0) {
      query = query.where(and(...conditions));
    }

    return query.orderBy(desc(weightRecords.recordedAt)).limit(limit).offset(skip);
  }

  async getWeightRecordById(id: string): Promise<WeightRecord | null> {
    const db = await getDb();
    const [record] = await db.select().from(weightRecords).where(eq(weightRecords.id, id));
    return record || null;
  }

  async deleteWeightRecord(id: string): Promise<boolean> {
    const db = await getDb();
    const result = await db.delete(weightRecords).where(eq(weightRecords.id, id));
    return (result.rowCount ?? 0) > 0;
  }

  async getLatestWeight(userId: string): Promise<number | null> {
    const db = await getDb();
    const [record] = await db
      .select()
      .from(weightRecords)
      .where(eq(weightRecords.userId, userId))
      .orderBy(desc(weightRecords.recordedAt))
      .limit(1);

    return record ? parseFloat(record.weight) : null;
  }

  async getWeightStats(userId: string): Promise<{
    currentWeight: number | null;
    startWeight: number | null;
    targetWeight: number | null;
  }> {
    const db = await getDb();

    const records = await db
      .select()
      .from(weightRecords)
      .where(eq(weightRecords.userId, userId))
      .orderBy(weightRecords.recordedAt)
      .limit(1);

    const currentWeight = await this.getLatestWeight(userId);
    const startWeight = records.length > 0 ? parseFloat(records[0].weight) : null;

    // 获取用户目标体重
    // 这里暂时返回 null，后续可以关联用户表
    const targetWeight = null;

    return {
      currentWeight,
      startWeight,
      targetWeight,
    };
  }
}

export const weightRecordManager = new WeightRecordManager();
