-- +goose Up
CREATE TABLE IF NOT EXISTS attachments (
  id BINARY(16) NOT NULL,
  file_id BINARY(16) NOT NULL,
  ref_type VARCHAR(64) NOT NULL,
  ref_id VARCHAR(191) NOT NULL,
  category VARCHAR(64) NULL,
  sort_order INT NOT NULL DEFAULT 0,
  is_primary TINYINT(1) NOT NULL DEFAULT 0,
  attached_by BINARY(16) NULL,
  created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
  PRIMARY KEY (id),
  CONSTRAINT fk_attachments_file
    FOREIGN KEY (file_id) REFERENCES file_files(id)
    ON UPDATE CASCADE
    ON DELETE CASCADE,
  UNIQUE KEY uq_attachments_ref_file (ref_type, ref_id, file_id),
  KEY idx_attachments_file_id (file_id),
  KEY idx_attachments_ref_sort (ref_type, ref_id, sort_order, created_at),
  KEY idx_attachments_ref_category (ref_type, ref_id, category)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- +goose Down
DROP TABLE IF EXISTS attachments;
