import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';
import { z } from '@hono/zod-openapi';

export type Permission = string;

export const RoleSchema = z.object({
  id: z.number().int().positive().openapi({
    description: '角色ID',
    example: 1
  }),
  name: z.string().max(50).openapi({
    description: '角色名称，唯一标识',
    example: 'admin'
  }),
  description: z.string().max(500).nullable().openapi({
    description: '角色描述',
    example: '系统管理员角色'
  }),
  permissions: z.array(z.string()).min(1).openapi({
    description: '角色权限列表',
    example: ['user:create', 'user:delete']
  }),
  createdAt: z.date().openapi({ description: '创建时间' }),
  updatedAt: z.date().openapi({ description: '更新时间' })
});

export const CreateRoleDto = RoleSchema.omit({ id: true , createdAt: true, updatedAt: true });
export const UpdateRoleDto = RoleSchema.partial();

@Entity({ name: 'role' })
export class Role {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column({ type: 'varchar', length: 50, unique: true })
  name!: string;

  @Column({ type: 'text', nullable: true })
  description!: string | null;

  @Column({ type: 'simple-array', nullable: false })
  permissions: Permission[] = [];

  @CreateDateColumn({ name: 'created_at', type: 'timestamp' })
  createdAt!: Date;

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamp' })
  updatedAt!: Date;

  constructor(partial?: Partial<Role>) {
    Object.assign(this, partial);
    if (!this.permissions) {
      this.permissions = [];
    }
  }
}