import { recordInfo } from "./record-info.js";
import { RepositoryBase } from "./base.js";
import { Flavor, UUID } from "../helpers";

export type UserId = Flavor<UUID, "User Id">;

export interface UnsavedUser {
  name: string;
  email: string;
  emailVerified: Date;
  avatar: string;
  isActive: boolean;
  userRole: string;
}

export interface SavedUser extends UnsavedUser {
  id: UserId;
  createdAt: Date;
  updatedAt: Date;
}

export const UserRecord = recordInfo<UnsavedUser, SavedUser>(
  "app_public",
  "users"
);

export class UserRecordRepository extends RepositoryBase(UserRecord) {
  async upsert(record: UnsavedUser | SavedUser): Promise<SavedUser> {
    return this.db.one(
      `INSERT INTO $1 ($2:name) VALUES ($2:csv)
       ON CONFLICT (email)
       DO UPDATE SET
          name = EXCLUDED.name,
          avatar = EXCLUDED.avatar,
          email_verified = EXCLUDED.email_verified
       RETURNING *`,
      [this.schemaTable, this.columnize(record)]
    );
  }
}
