import {
    pgTable,
    bigint,
    text,
    timestamp,
    boolean,
    jsonb,
    uuid,
} from "drizzle-orm/pg-core"

import { tenants } from "./tenants"
import { customers } from "./customers"
import { contacts } from "./contacts"
import { contracttypes } from "./contracttypes"
import { authUsers } from "./auth_users"
import { outgoingsepamandates } from "./outgoingsepamandates"

export const contracts = pgTable(
    "contracts",
    {
        id: bigint("id", { mode: "number" })
            .primaryKey()
            .generatedByDefaultAsIdentity(),

        createdAt: timestamp("created_at", { withTimezone: true })
            .notNull()
            .defaultNow(),

        tenant: bigint("tenant", { mode: "number" }).notNull(),

        name: text("name").notNull(),

        customer: bigint("customer", { mode: "number" })
            .notNull()
            .references(() => customers.id),

        notes: text("notes"),

        active: boolean("active").notNull().default(true),
        recurring: boolean("recurring").notNull().default(false),

        rhythm: jsonb("rhythm"),

        startDate: timestamp("startDate", { withTimezone: true }),
        endDate: timestamp("endDate", { withTimezone: true }),
        signDate: timestamp("signDate", { withTimezone: true }),

        duration: text("duration"),

        contact: bigint("contact", { mode: "number" }).references(
            () => contacts.id
        ),
        contracttype: bigint("contracttype", { mode: "number" }).references(
            () => contracttypes.id
        ),
        allowedContracttypes: jsonb("allowedContracttypes").notNull().default([]),

        bankingIban: text("bankingIban"),
        bankingBIC: text("bankingBIC"),
        bankingName: text("bankingName"),
        bankingOwner: text("bankingOwner"),
        sepaRef: text("sepaRef"),
        sepaDate: timestamp("sepaDate", { withTimezone: true }),
        outgoingsepamandate: bigint("outgoingsepamandate", { mode: "number" }).references(
            () => outgoingsepamandates.id
        ),

        paymentType: text("paymentType"),
        billingInterval: text("billingInterval"),
        invoiceDispatch: text("invoiceDispatch"),

        ownFields: jsonb("ownFields").notNull().default({}),
        profiles: jsonb("profiles").notNull().default([]),

        archived: boolean("archived").notNull().default(false),

        contractNumber: text("contractNumber"),

        updatedAt: timestamp("updated_at", { withTimezone: true }),

        updatedBy: uuid("updated_by").references(() => authUsers.id),
    }
)

export type Contract = typeof contracts.$inferSelect
export type NewContract = typeof contracts.$inferInsert
