import { pgTable, text, timestamp, uuid, bigint } from "drizzle-orm/pg-core";
import { InferModel } from "drizzle-orm";
import { organisation } from "./organisation";
import { user } from "./users";
import { portfolio, roleEnum } from "./portfolio";

export const team = pgTable("team", {
  id: uuid("id").defaultRandom().primaryKey(),
  name: text("name").notNull(),
  orgId: uuid("org_id")
    .notNull()
    .references(() => organisation.id),
  createdAt: timestamp("created_at", { precision: 6, withTimezone: true })
    .defaultNow()
    .notNull(),
  updatedAt: timestamp("updated_at", { precision: 6, withTimezone: true })
    .defaultNow()
    .notNull(),
});

export const teamMembers = pgTable("team_members", {
  id: uuid("id").defaultRandom().primaryKey(),
  userId: bigint("user_id", { mode: "bigint" })
    .notNull()
    .references(() => user.id),
  teamId: uuid("team_id")
    .notNull()
    .references(() => team.id),
  createdAt: timestamp("created_at", { precision: 6, withTimezone: true })
    .defaultNow()
    .notNull(),
  updatedAt: timestamp("updated_at", { precision: 6, withTimezone: true })
    .defaultNow()
    .notNull(),
});

export const teamPortfolioPermissions = pgTable("team_portfolio_permissions", {
  id: uuid("id").defaultRandom().primaryKey(),
  teamId: uuid("team_id")
    .notNull()
    .references(() => team.id),
  portfolioId: bigint("portfolio_id", { mode: "bigint" })
    .notNull()
    .references(() => portfolio.id),
  role: roleEnum("role").notNull(),
  createdAt: timestamp("created_at", { precision: 6, withTimezone: true })
    .defaultNow()
    .notNull(),
  updatedAt: timestamp("updated_at", { precision: 6, withTimezone: true })
    .defaultNow()
    .notNull(),
});

export type Team = InferModel<typeof team, "select">;
export type NewTeam = InferModel<typeof team, "insert">;
export type TeamMembers = InferModel<typeof teamMembers, "select">;
export type NewTeamMembers = InferModel<typeof teamMembers, "insert">;
export type TeamPortfolioPermissions = InferModel<
  typeof teamPortfolioPermissions,
  "select"
>;
export type NewTeamPortfolioPermissions = InferModel<
  typeof teamPortfolioPermissions,
  "insert"
>;
