/**
 * آدرس‌های کاربر. نام گیرنده، موبایل، نشانی و کد پستی با AES-256-GCM رمزگذاری‌شده ذخیره می‌شوند.
 */
import "server-only";
import { db } from "@/lib/db";
import { decrypt, encrypt } from "@/lib/crypto";
import { addressSchema } from "@/validation/common";
import type { z } from "zod";

export interface AddressDTO {
  id: string;
  title: string;
  receiver: string;
  phone: string;
  province: string;
  city: string;
  line: string;
  postalCode: string;
}

export async function listAddresses(userId: string): Promise<AddressDTO[]> {
  const rows = await db.address.findMany({ where: { userId }, orderBy: { createdAt: "asc" } });
  return rows.map((a) => ({
    id: a.id,
    title: a.title,
    province: a.province,
    city: a.city,
    receiver: decrypt(a.receiver),
    phone: decrypt(a.phone),
    line: decrypt(a.line),
    postalCode: decrypt(a.postalCode),
  }));
}

export async function saveAddress(userId: string, input: z.output<typeof addressSchema>, id?: string) {
  const data = {
    title: input.title,
    province: input.province,
    city: input.city,
    receiver: encrypt(input.receiver),
    phone: encrypt(input.phone),
    line: encrypt(input.line),
    postalCode: encrypt(input.postalCode),
  };
  // ویرایش فقط وقتی آدرس متعلق به همین کاربر باشد
  const owned = id ? await db.address.findFirst({ where: { id, userId }, select: { id: true } }) : null;
  const row = owned ? await db.address.update({ where: { id: owned.id }, data }) : await db.address.create({ data: { ...data, userId } });
  return row.id;
}

export async function deleteAddress(userId: string, id: string) {
  await db.address.deleteMany({ where: { id, userId } });
}
