import { pgTable, text, varchar, timestamp, boolean, integer, decimal, jsonb, index } from "drizzle-orm/pg-core";
import { sql } from "drizzle-orm";
import { createSchemaFactory } from "drizzle-zod";
import { z } from "zod";

// 用户表
export const users = pgTable(
  "users",
  {
    id: varchar("id", { length: 36 })
      .primaryKey()
      .default(sql`gen_random_uuid()`),
    name: varchar("name", { length: 128 }).notNull(),
    gender: varchar("gender", { length: 10 }), // 'male' | 'female' | 'other'
    age: integer("age"),
    height: integer("height"), // 身高（厘米）
    targetWeight: decimal("target_weight", { precision: 5, scale: 2 }), // 目标体重（千克）
    currentWeight: decimal("current_weight", { precision: 5, scale: 2 }), // 当前体重（千克）
    metadata: jsonb("metadata"),
    createdAt: timestamp("created_at", { withTimezone: true })
      .defaultNow()
      .notNull(),
    updatedAt: timestamp("updated_at", { withTimezone: true }),
  },
  (table) => ({
    nameIdx: index("users_name_idx").on(table.name),
  })
);

// 食物记录表
export const foodRecords = pgTable(
  "food_records",
  {
    id: varchar("id", { length: 36 })
      .primaryKey()
      .default(sql`gen_random_uuid()`),
    userId: varchar("user_id", { length: 36 }).notNull(),
    foodName: varchar("food_name", { length: 256 }).notNull(),
    calories: integer("calories").notNull(), // 热量（千卡）
    weight: decimal("weight", { precision: 5, scale: 2 }), // 重量（克）
    imageUrl: text("image_url"), // 食物图片 URL
    mealType: varchar("meal_type", { length: 20 }).notNull(), // 'breakfast' | 'lunch' | 'dinner' | 'snack'
    recordedAt: timestamp("recorded_at", { withTimezone: true }).notNull(), // 记录时间
    createdAt: timestamp("created_at", { withTimezone: true })
      .defaultNow()
      .notNull(),
  },
  (table) => ({
    userIdIdx: index("food_records_user_id_idx").on(table.userId),
    recordedAtIdx: index("food_records_recorded_at_idx").on(table.recordedAt),
  })
);

// 体重记录表
export const weightRecords = pgTable(
  "weight_records",
  {
    id: varchar("id", { length: 36 })
      .primaryKey()
      .default(sql`gen_random_uuid()`),
    userId: varchar("user_id", { length: 36 }).notNull(),
    weight: decimal("weight", { precision: 5, scale: 2 }).notNull(), // 体重（千克）
    note: text("note"), // 备注
    recordedAt: timestamp("recorded_at", { withTimezone: true }).notNull(), // 记录时间
    createdAt: timestamp("created_at", { withTimezone: true })
      .defaultNow()
      .notNull(),
  },
  (table) => ({
    userIdIdx: index("weight_records_user_id_idx").on(table.userId),
    recordedAtIdx: index("weight_records_recorded_at_idx").on(table.recordedAt),
  })
);

// 使用 createSchemaFactory 配置 date coercion（处理前端 string → Date 转换）
const { createInsertSchema: createCoercedInsertSchema } = createSchemaFactory({
  coerce: { date: true },
});

// Users schemas
export const insertUserSchema = createCoercedInsertSchema(users).pick({
  name: true,
  gender: true,
  age: true,
  height: true,
  targetWeight: true,
  currentWeight: true,
  metadata: true,
});

export const updateUserSchema = createCoercedInsertSchema(users)
  .pick({
    name: true,
    gender: true,
    age: true,
    height: true,
    targetWeight: true,
    currentWeight: true,
  })
  .partial();

// Food records schemas
export const insertFoodRecordSchema = createCoercedInsertSchema(foodRecords).pick({
  userId: true,
  foodName: true,
  calories: true,
  weight: true,
  imageUrl: true,
  mealType: true,
  recordedAt: true,
});

// Weight records schemas
export const insertWeightRecordSchema = createCoercedInsertSchema(weightRecords).pick({
  userId: true,
  weight: true,
  note: true,
  recordedAt: true,
});

// TypeScript types
export type User = typeof users.$inferSelect;
export type InsertUser = z.infer<typeof insertUserSchema>;
export type UpdateUser = z.infer<typeof updateUserSchema>;

export type FoodRecord = typeof foodRecords.$inferSelect;
export type InsertFoodRecord = z.infer<typeof insertFoodRecordSchema>;

export type WeightRecord = typeof weightRecords.$inferSelect;
export type InsertWeightRecord = z.infer<typeof insertWeightRecordSchema>;
